Deleting an element from an array in PHP

后端 未结 30 3275
时光说笑
时光说笑 2020-11-21 05:55

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it

30条回答
  •  说谎
    说谎 (楼主)
    2020-11-21 06:33

    If you need to remove multiple elements from an associative array, you can use array_diff_key() (here used with array_flip()):

    $my_array = array(
      "key1" => "value 1",
      "key2" => "value 2",
      "key3" => "value 3",
      "key4" => "value 4",
      "key5" => "value 5",
    );
    
    $to_remove = array("key2", "key4");
    
    $result = array_diff_key($my_array, array_flip($to_remove));
    
    print_r($result);
    

    Output:

    Array ( [key1] => value 1 [key3] => value 3 [key5] => value 5 ) 
    

提交回复
热议问题