How to insert an item at the beginning of an array in PHP?

后端 未结 9 782
萌比男神i
萌比男神i 2020-12-02 14:53

I know how to insert it to the end by:

$arr[] = $item;

But how to insert it to the beginning?

相关标签:
9条回答
  • 2020-12-02 15:38

    In case of an associative array or numbered array where you do not want to change the array keys:

    $firstItem = array('foo' => 'bar');
    
    $arr = $firstItem + $arr;
    

    array_merge does not work as it always reindexes the array.

    0 讨论(0)
  • 2020-12-02 15:39

    Use array_unshift() to insert the first element in an array.

    User array_shift() to removes the first element of an array.

    0 讨论(0)
  • 2020-12-02 15:44

    Or you can use temporary array and then delete the real one if you want to change it while in cycle:

    $array = array(0 => 'a', 1 => 'b', 2 => 'c');
    $temp_array = $array[1];
    
    unset($array[1]);
    array_unshift($array , $temp_array);
    

    the output will be:

    array(0 => 'b', 1 => 'a', 2 => 'c')
    

    and when are doing it while in cycle, you should clean $temp_array after appending item to array.

    0 讨论(0)
提交回复
热议问题