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

后端 未结 9 821
萌比男神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.

提交回复
热议问题