PHP array delete by value (not key)

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

    Using array_search() and unset, try the following:

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

    array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

    The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

提交回复
热议问题