PHP - add item to beginning of associative array [duplicate]

Solution 1:

You could use the union operator:

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

or array_merge.

Solution 2:

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:

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

Solution 4:

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

    return $array;
}

Solution 5:

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