Array_unshift like function that returns the array

1k views Asked by At

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?

3

There are 3 answers

0
Arialdo Martini On BEST ANSWER

You could use

array_merge()

For example

$resultingArray = array_merge(array($newElement), $originalArray);
0
Michael Berkowski On

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
)
0
hakre On

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 operator­Docs.