Table of contents

PHP: Insert an element with the specified key at the beginning of the array

PHP May 15, 2021 Viewed 14 Comments 0

Issue

With array_unshift(), we can prepend one or more elements to the beginning of an array. All numerical array keys will be modified to start counting from zero while literal keys won't be changed.

$arr = [
    "key2" => 2,
    "3" => 3
];
array_unshift($arr, 1, 100);
print_r($arr);

Output:

Array
(
    [0] => 1
    [1] => 100
    [key2] => 2
    [2] => 3
)

It is not possible to add an element with the specified key at the front of the array using array_unshift() or array_marge().

Solution

The + operator won't reindex the keys in array. For example.

$arr = [
    "key2" => 2,
    "3" => 3
];
$arr = [1 => 1, 100 => 100] + $arr;
print_r($arr);

Output:

Array
(
    [1] => 1
    [100] => 100
    [key2] => 2
    [3] => 3
)
Updated May 15, 2021