I know how to insert it to the end by:
$arr[] = $item;
But how to insert it to the beginning?
Join Stack Overflow to learn, share knowledge, and build your career.
I know how to insert it to the end by:
$arr[] = $item;
But how to insert it to the beginning?
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
)
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 4 '15 at 23:23
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'
]
For an associative array you can just use merge.
$arr = array('item2', 'item3', 'item4');
$arr = array_merge(array('item1'), $arr)
Use array_unshift() to insert the first element in an array.
User array_shift() to removes the first element of an array.
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.
$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"]
)
$arr[-1] = $item;
Found here: stackoverflow.com/a/15252657/669677 – user669677 Jul 4 '13 at 14:22print_r($arr)
=>Array ( [0] => a, [1] => b, [-1] => c )
– laurent Jan 28 '14 at 7:07for ($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. – user669677 Jan 28 '14 at 9:13