Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

People also ask

How do you put an element at the start of an array?

The unshift() method adds new elements to the beginning of an array.

How can get first and last value in array in PHP?

You can use the end() function in PHP to get the last element of any PHP array. It will set the internal pointer to the last element of the array and return its value.

What is Array_push in PHP?

Definition and Usage. The array_push() function inserts one or more elements to the end of an array. Tip: You can add one value, or as many as you like. Note: Even if your array has string keys, your added elements will always have numeric keys (See example below).


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.


For an associative array you can just use merge.

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

Insert an item in the beginning of an associative array with string/custom key

<?php

$array = ['keyOne'=>'valueOne', 'keyTwo'=>'valueTwo'];

$array = array_reverse($array);

$array['newKey'] = 'newValue';

$array = array_reverse($array);

RESULT

[
  'newKey' => 'newValue',
  'keyOne' => 'valueOne',
  'keyTwo' => 'valueTwo'
]