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

I know how to insert it to the end by:

$arr[] = $item;

But how to insert it to the beginning?


Use array_unshift($array, $item);

$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);

will give you

Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

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.


使用函数array_unshift

链接地址: http://www.djcxy.com/p/58944.html

上一篇: 数组有什么区别

下一篇: 如何在PHP的数组的开头插入一个项目?