PHP array delete by value (not key)

前端 未结 19 2097
花落未央
花落未央 2020-11-22 15:58

I have a PHP array as follows:

$messages = [312, 401, 1599, 3, ...];

I want to delete the element containing the value $del_val

19条回答
  •  臣服心动
    2020-11-22 16:21

    I think the simplest way would be to use a function with a foreach loop:

    //This functions deletes the elements of an array $original that are equivalent to the value $del_val
    //The function works by reference, which means that the actual array used as parameter will be modified.
    
    function delete_value(&$original, $del_val)
    {
        //make a copy of the original, to avoid problems of modifying an array that is being currently iterated through
        $copy = $original;
        foreach ($original as $key => $value)
        {
            //for each value evaluate if it is equivalent to the one to be deleted, and if it is capture its key name.
            if($del_val === $value) $del_key[] = $key;
        };
        //If there was a value found, delete all its instances
        if($del_key !== null)
        {
            foreach ($del_key as $dk_i)
            {
                unset($original[$dk_i]);
            };
            //optional reordering of the keys. WARNING: only use it with arrays with numeric indexes!
            /*
            $copy = $original;
            $original = array();
            foreach ($copy as $value) {
                $original[] = $value;
            };
            */
            //the value was found and deleted
            return true;
        };
        //The value was not found, nothing was deleted
        return false;
    };
    
    $original = array(0,1,2,3,4,5,6,7,4);
    $del_val = 4;
    var_dump($original);
    delete_value($original, $del_val);
    var_dump($original);
    

    Output will be:

    array(9) {
      [0]=>
      int(0)
      [1]=>
      int(1)
      [2]=>
      int(2)
      [3]=>
      int(3)
      [4]=>
      int(4)
      [5]=>
      int(5)
      [6]=>
      int(6)
      [7]=>
      int(7)
      [8]=>
      int(4)
    }
    array(7) {
      [0]=>
      int(0)
      [1]=>
      int(1)
      [2]=>
      int(2)
      [3]=>
      int(3)
      [5]=>
      int(5)
      [6]=>
      int(6)
      [7]=>
      int(7)
    }
    

提交回复
热议问题