PHP prepend associative array with literal keys?

PhpArraysAssociative Array

Php Problem Overview


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');

Php Solutions


Solution 1 - Php

Can't you just do:

$resulting_array = $array2 + $array1;

?

Solution 2 - Php

You cannot directly 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.

Solution 3 - Php

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);

Solution 4 - Php

Using the same method as @mvpetrovich, you can use the shorthand version of an array to shorten the syntax.

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

References:

PHP: array_merge()

PHP: Arrays - Manual

> As of PHP 5.4 you can also use the short array syntax, which replaces array() with [].

Solution 5 - Php

@Cletus is spot on. Just to add, if the ordering of the elements in the input arrays are ambiguous, and you need the final array to be sorted, you might want to ksort:

$resulting_array = $array1 + $array2;
ksort($resulting_array);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionColin BrockView Question on Stackoverflow
Solution 1 - PhpcletusView Answer on Stackoverflow
Solution 2 - PhpPHPguruView Answer on Stackoverflow
Solution 3 - PhpmvpetrovichView Answer on Stackoverflow
Solution 4 - PhpBryce GoughView Answer on Stackoverflow
Solution 5 - Phpkarim79View Answer on Stackoverflow