Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array_unshift like function that returns the array

Tags:

arrays

php

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?

like image 712
Anna K. Avatar asked May 30 '26 11:05

Anna K.


2 Answers

You could use

array_merge()

For example

$resultingArray = array_merge(array($newElement), $originalArray);
like image 169
Arialdo Martini Avatar answered Jun 02 '26 01:06

Arialdo Martini


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.

like image 42
hakre Avatar answered Jun 02 '26 01:06

hakre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!