PHP prepend associative array with literal keys? PHP prepend associative array with literal keys? arrays arrays

PHP prepend associative array with literal keys?


Can't you just do:

$resulting_array = $array2 + $array1;

?


The answer is no. You cannot prepend an associative array with a key-value pair.

However you can create a new array that contains the new key-value pair at the beginning of the array with the union operator +. The outcome is an entirely new array though and creating the new array has O(n) complexity.

The syntax is below.

$new_array = array('new_key' => 'value') + $original_array;

Note: Do not use array_merge(). array_merge() overwrites keys and does not preserve numeric keys.


In your situation, you want to use array_merge():

array_merge(array('fruit1'=>'cherry', 'fruit2'=>'blueberry'), array('fruit3'=>'apple', 'fruit4'=>'orange'));

To prepend a single value, for an associative array, instead of array_unshift(), again use array_merge():

array_merge(array($key => $value), $myarray);