277

I know how to insert it to the end by:

$arr[] = $item;

But how to insert it to the beginning?

Achraf JEDAY
  • 1,936
  • 5
  • 24
  • 33
web
  • 2,803
  • 2
  • 15
  • 5
  • 3
    `$arr[-1] = $item;` Found here: http://stackoverflow.com/a/15252657/669677 –  Jul 04 '13 at 14:22
  • 4
    @2astalavista, that doesn't work: `print_r($arr)` => `Array ( [0] => a, [1] => b, [-1] => c )` – laurent Jan 28 '14 at 07:07
  • @returnthis.lau_ this case you should use for loop - starting from -1 - to make it work: `for ($i = -1; $i < count($a)-1; $i++)` as the referenced link showed, but it is easy to forget, so I don't prefer that solution any more. –  Jan 28 '14 at 09:13

8 Answers8

464

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
)
Toby Allen
  • 10,997
  • 11
  • 73
  • 124
Trav L
  • 14,732
  • 6
  • 30
  • 39
  • 7
    What about if you need literal, rather than numeric, keys? – Evan Dec 06 '13 at 04:52
  • 4
    @Evan, the documentation for `array_unshift` says the following `All numerical array keys will be modified to start counting from zero while literal keys won't be touched.` – craned Dec 04 '15 at 23:23
  • 1
    There are two problem: 1)reindexing the array 2)can not add item with an index. – Nabi K.A.Z. Jun 13 '19 at 21:23
  • 2
    If you have an associative array or need to preserve keys then see the user examples here: https://www.php.net/manual/en/function.array-unshift.php there are a couple good examples of how to accomplish this! – Vallier Aug 22 '19 at 21:59
152

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.

tihe
  • 2,452
  • 3
  • 25
  • 27
  • 9
    Attention! "The + operator returns the right-hand array appended to the left-hand array; for keys that exist in both arrays, the elements from the left-hand array will be used, and the matching elements from the right-hand array will be ignored." -- See: https://stackoverflow.com/a/2140094/3411766 – cottton Apr 12 '18 at 12:42
  • The solution it's good because can add item with an index, and didn't reindexing the array; But have just a note about remove item in the right hand array, if there are same index in the left hand array. – Nabi K.A.Z. Jun 13 '19 at 21:27
17

Since PHP7.4 you can use the spread opperator, very similar to JavaScript

$arr = [$item, ...$arr];

https://wiki.php.net/rfc/spread_operator_for_array

A few more examples:

// Add an item before
$arr = [$item, ...$arr];

// Add an item after
$arr = [...$arr, $item];

// Add a few more
$arr = [$item1, $item2, ...$arr, $item3];

// Multiple arrays and and items
$arr = [$item1, ...$arr1, $item2, ...$arr2, $item3];
  • Note: this is only possible with int keys, not for associative arrays.
  • Note2: The keys are not kept.

BREAKING Example:

$car = ['brand' => 'Audi', 'model' => 'A8'];
$engine = ['cylinder' => 6, 'displacement' => '3000cc'];

$merged = [...$car, ...$engine];

var_dump($merged);

Will result in:

[ Error ] Cannot unpack array with string keys

nito
  • 1,157
  • 8
  • 21
14

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'
]
Manish Dhruw
  • 753
  • 9
  • 18
14

For an associative array you can just use merge.

$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)
pictoru
  • 722
  • 6
  • 17
8

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

Use array_shift() to remove the first element of an array.

Rohit Gupta
  • 4,022
  • 20
  • 31
  • 41
Vinit Kadkol
  • 1,221
  • 13
  • 12
7

There are two solutions:

  1. if you have array with keys that matter to you
$new = ['RLG' => array(1,2,3)];
$array = ['s' => array(2,3), 'l' => [], 'o' => [], 'e' => []];

$arrayWithNewAddedItem = array_merge($new, $array);
  1. if you have an array without any keys.
array_unshift(array, value1);
Farid shahidi
  • 318
  • 4
  • 9
4

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.

Arnas Pečelis
  • 1,000
  • 2
  • 12
  • 32