Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 218
teepusink Avatar asked Apr 25 '11 22:04

teepusink


People also ask

How do you add an element in the beginning of an associative array in PHP?

Use the array_merge() Function to Add Elements at the Beginning of an Associative Array in PHP. To add elements at the beginning of an associative, we can use the array union of the array_merge() function.

Can associative array have same key?

No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.

How do you get the first key of an associative array?

Starting from PHP 7.3, there is a new built in function called array_key_first() which will retrieve the first key from the given array without resetting the internal pointer. Check out the documentation for more info. You can use reset and key : reset($array); $first_key = key($array);


5 Answers

You could use the union operator:

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

or array_merge.

like image 69
Felix Kling Avatar answered Oct 01 '22 01:10

Felix Kling


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.

like image 21
outis Avatar answered Oct 01 '22 00:10

outis


$array = array('key1' => 'value1', 'key2' => 'value2');
array_combine(array_unshift(array_keys($array),'key0'),array_unshift(array_values($array),'value0'))
like image 28
Mark Baker Avatar answered Oct 01 '22 01:10

Mark Baker


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

    return $array;
}
like image 44
Tomek Avatar answered Oct 01 '22 01:10

Tomek


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

like image 39
James C Avatar answered Oct 01 '22 02:10

James C