[php] 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?

This question is related to php arrays

The answer is


With custom index:

$arr=array("a"=>"one", "b"=>"two");
    $arr=array("c"=>"three", "d"=>"four").$arr;

    print_r($arr);
    -------------------
    output:
    ----------------
    Array
    (
    [c]=["three"]
    [d]=["four"]
    [a]=["two"]
    [b]=["one"]
    )

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.


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.


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'
]

Use function array_unshift


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

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


This will help

http://www.w3schools.com/php/func_array_unshift.asp

array_unshift();

For an associative array you can just use merge.

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