Reputation: 1995
is there a built in function in php that prepends an element to an array, and returns the new array?
instead of returning the new length of the array?
Upvotes: 3
Views: 1139
Reputation: 270707
There's no built-in which does it, but it's simple enough to wrap it:
function my_unshift($array, $var) {
array_unshift($array, $var);
return $array;
}
This isn't necessary though, because array_unshift()
operates on an array reference so the original is modified in place. array_push(), array_pop(), array_shift()
all also operate on a a reference.
$arr = array(1,2,3);
array_unshift($arr, 0);
// No need for return. $arr has been modified
print_arr($arr);
Array
(
[0] => 0
[1] => 1
[2] => 2
[3] => 3
)
Upvotes: 2
Reputation: 198131
Next to array_merge
, if there ain't any duplicate keys, you can do:
$array = array('a' => 'A');
$append = array('b' => 'hello');
$array = $append + $array;
Gives:
Array
(
[b] => hello
[a] => A
)
The plus is the array union operatorDocs.
Upvotes: 3
Reputation: 4567
You could use
array_merge()
For example
$resultingArray = array_merge(array($newElement), $originalArray);
Upvotes: 6