PHP - add item to beginning of associative array

Php

Php Problem Overview


How can I add an item to the beginning of an associative array? For example, say I have an array like this:

$arr = array('key1' => 'value1', 'key2' => 'value2');

When I add something to it as in $arr['key0'] = 'value0';, I get:

Array
(
[key1] => value1
[key2] => value2
[key0] => value0
)

How do I make that to be

Array
(
[key0] => value0
[key1] => value1
[key2] => value2
)

Thanks,
Tee

Php Solutions


Solution 1 - Php

You could use the union operator:

$arr1 = array('key0' => 'value0') + $arr1;

or array_merge.

Solution 2 - Php

One way is with array_merge:

<?php
$arr = array('key1' => 'value1', 'key2' => 'value2');
$arr = array_merge(array('key0' => 'value0'), $arr);

Depending on circumstances, you may also make use of ksort.

Solution 3 - Php

$array = array('key1' => 'value1', 'key2' => 'value2');
array_combine(array_unshift(array_keys($array),'key0'),array_unshift(array_values($array),'value0'))

Solution 4 - Php

function unshift( array & $array, $key, $val)
{
	$array = array_reverse($array, 1);
	$array[$key] = $val;
	$array = array_reverse($array, 1);

	return $array;
}

Solution 5 - Php

If you don't want to merge the arrays you could just use ksort() on the array before iterating over it.

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
QuestionteepusinkView Question on Stackoverflow
Solution 1 - PhpFelix KlingView Answer on Stackoverflow
Solution 2 - PhpoutisView Answer on Stackoverflow
Solution 3 - PhpMark BakerView Answer on Stackoverflow
Solution 4 - PhpTomekView Answer on Stackoverflow
Solution 5 - PhpJames CView Answer on Stackoverflow