$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.
For an associative array you can just use merge.
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)
Source: Stackoverflow.com