Deleting an element from an array in PHP

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

    Two ways for removing the first item of an array with keeping order of the index and also if you don't know the key name of the first item.

    Solution #1

    // 1 is the index of the first object to get
    // NULL to get everything until the end
    // true to preserve keys
    $array = array_slice($array, 1, null, true);
    

    Solution #2

    // Rewinds the array's internal pointer to the first element
    // and returns the value of the first array element.
    $value = reset($array);
    // Returns the index element of the current array position
    $key = key($array);
    unset($array[$key]);
    

    For this sample data:

    $array = array(10 => "a", 20 => "b", 30 => "c");
    

    You must have this result:

    array(2) {
      [20]=>
      string(1) "b"
      [30]=>
      string(1) "c"
    }
    

提交回复
热议问题