PHP prepend associative array with literal keys?

04/13/2020 17:00:02

Is it possible to prepend an associative array with literal key=>value pairs? I know that array_unshift() works with numerical keys, but I'm hoping for something that will work with literal keys.

As an example I'd like to do the following:

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

// prepend magic

$resulting_array = ('fruit1'=>'cherry', 
                    'fruit2'=>'blueberry', 
                    'fruit3'=>'apple', 
                    'fruit4'=>'orange');

Verified Answer (210 Votes)

09/03/2009 07:29:35

Can't you just do:

$resulting_array = $array2 + $array1;

?

210

Answer #2 (28 Votes)

03/23/2015 23:47:54

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.

28

Answer #3 (16 Votes)

08/25/2012 22:52:00

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);
16
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.