Deleting an element from an array in PHP

后端 未结 30 3277
时光说笑
时光说笑 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:34

      // Our initial array
      $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");
      print_r($arr);
    
      // Remove the elements who's values are yellow or red
      $arr = array_diff($arr, array("yellow", "red"));
      print_r($arr);
    

    This is the output from the code above:

    Array
    (
        [0] => blue
        [1] => green
        [2] => red
        [3] => yellow
        [4] => green
        [5] => orange
        [6] => yellow
        [7] => indigo
        [8] => red
    )
    
    Array
    (
        [0] => blue
        [1] => green
        [4] => green
        [5] => orange
        [7] => indigo
    )
    

    Now, array_values() will reindex a numerical array nicely, but it will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():

    $arr = array_merge(array_diff($arr, array("yellow", "red")));
    print_r($arr);
    

    Outputs

    Array
    (
        [0] => blue
        [1] => green
        [2] => green
        [3] => orange
        [4] => indigo
    )
    

提交回复
热议问题