I know how to insert it to the end by:
$arr[] = $item;
But how to insert it to the beginning?
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'
]
This will help
http://www.w3schools.com/php/func_array_unshift.asp
array_unshift();
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
)
For an associative array you can just use merge.
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)
Use function array_unshift
$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"]
)