PHP array delete by value (not key)

前端 未结 19 2002
花落未央
花落未央 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:22

    If you know for definite that your array will contain only one element with that value, you can do

    $key = array_search($del_val, $array);
    if (false !== $key) {
        unset($array[$key]);
    }
    

    If, however, your value might occur more than once in your array, you could do this

    $array = array_filter($array, function($e) use ($del_val) {
        return ($e !== $del_val);
    });
    

    Note: The second option only works for PHP5.3+ with Closures

提交回复
热议问题