PHP array delete by value (not key)

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

    0 讨论(0)
  • 2020-11-22 16:22

    To delete multiple values try this one:

    while (($key = array_search($del_val, $messages)) !== false) 
    {
        unset($messages[$key]);
    }
    
    0 讨论(0)
  • 2020-11-22 16:22

    As per your requirement "each value can only be there for once" if you are just interested in keeping unique values in your array, then the array_unique() might be what you are looking for.

    Input:

    $input = array(4, "4", "3", 4, 3, "3");
    $result = array_unique($input);
    var_dump($result);
    

    Result:

    array(2) {
      [0] => int(4)
      [2] => string(1) "3"
    }
    
    0 讨论(0)
  • 2020-11-22 16:23
    function array_remove_by_value($array, $value)
    {
        return array_values(array_diff($array, array($value)));
    }
    
    $array = array(312, 401, 1599, 3);
    
    $newarray = array_remove_by_value($array, 401);
    
    print_r($newarray);
    

    Output

    Array ( [0] => 312 [1] => 1599 [2] => 3 )

    0 讨论(0)
  • 2020-11-22 16:25
    $fields = array_flip($fields);
    unset($fields['myvalue']);
    $fields = array_flip($fields);
    
    0 讨论(0)
  • 2020-11-22 16:29

    here is one simple but understandable solution:

    $messagesFiltered = [];
    foreach ($messages as $message) {
        if (401 != $message) {
            $messagesFiltered[] = $message;
        }
    }
    $messages = $messagesFiltered;
    
    0 讨论(0)
提交回复
热议问题