Coder Perfect

PHP prepend associative array with literal keys?


Is it feasible to prepend a literal key=>value pair to an associative array? I know array unshift() works with number keys, but I’m expecting for something that works with literal keys as well.

As an example, here’s what I’d like to do:

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

// prepend magic

$resulting_array = ('fruit1'=>'cherry', 

Asked by Colin Brock

Solution #1

Why don’t you just:

$resulting_array = $array2 + $array1;


Answered by cletus

Solution #2

A key-value pair cannot be explicitly prepended to an associative array.

The union operator +, on the other hand, can be used to build a new array with the new key-value pair at the beginning. However, the result is a whole new array, and building the new array is O(n) in complexity.

The syntax is shown below.

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

Note: array merge should not be used (). numeric keys are not preserved when using array merge() since it overwrites them.

Answered by PHPguru

Solution #3

You should use array merge() in your situation:

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

Instead of array unshift(), use array merge() to prepend a single value to an associative array:

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

Answered by mvpetrovich

Solution #4

You may use the shorthand version of an array to shorten the syntax in the same way that @mvpetrovich did.

$_array = array_merge(["key1" => "key_value"], $_old_array);


PHP: array_merge()

Manual for PHP Arrays

Answered by Bryce Gough

Solution #5

@Cletus is absolutely correct. Just a note: if the ordering of the elements in the input arrays is questionable and you need the final array to be sorted, you should use ksort:

$resulting_array = $array1 + $array2;

Answered by karim79

Post is based on