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?
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.
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
)
Nowadays you can use the spread operator.
$new_array = ['a', ...['b', 'c', 'd']];
assert($new_array === ['a', 'b', 'c', 'd']);
Be careful what this does with array keys!
https://3v4l.org/b03HU
array_unshift?print_r($var_arr)to get the array.print_ris not for "getting array", its for printingarray_unshif? You can copy an array by assigning it to a new variable:$copy = $array; array_unshift($array);.