3

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?

4
  • 1
    whats wrong with using array variable that still pass to array_unshift? Commented Apr 11, 2012 at 12:27
  • Array unshift edits the original array and then returns the size of it. You can later use a print_r($var_arr) to get the array. Commented Apr 11, 2012 at 12:28
  • @TheJumpingFrog no, print_r is not for "getting array", its for printing Commented Apr 11, 2012 at 12:32
  • @Anna K. - What's wrong with array_unshif? You can copy an array by assigning it to a new variable: $copy = $array; array_unshift($array);. Commented Apr 11, 2012 at 18:50

4 Answers 4

6

You could use

array_merge()

For example

$resultingArray = array_merge(array($newElement), $originalArray);
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

2

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
)

Comments

0

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

1 Comment

Note that spreading will work with non-numeric keys from PHP8.1 and up. 3v4l.org/XP6YJ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.