Unshifting PHP Arrays Without Losing Keys
When working with associative arrays in PHP, removing elements can be tricky if you care about preserving their keys. The most common tool for removing the first element is array_shift(), but it comes with a specific behavior: it re-indexes the remaining array starting from zero and resets all keys to sequential integers.
If your array looks like this:
$array = [
'a' => '123',
'b' => '234',
'c' => '345'
];
Running array_shift($array) produces:
Array (
[0] => 234,
[1] => 345
)
The original string keys 'a', 'b', and 'c' are lost. If you need to retain themâso that the result is:
Array (
['b'] => '234',
['c'] => '345'
)
âyou cannot use `array_shift()`. You must use `array_splice()` instead.
### Why `array_splice()` Preserves Keys
The `array_splice()` function removes elements from an array at a specified offset and optionally replaces them. When removing the first element by calling `array_splice($array, 0, 1)`, it deletes the element at index 0 while leaving the rest of the array untouched. Crucially, `array_splice()` does not re-index the remaining elements; it keeps their original keys intact.
For the first example:
```php
$array = [
'a' => '123',
'b' => '234',
'c' => '345'
];
array_splice($array, 0, 1);
// Result:
// Array (
// ['b'] => '234',
// ['c'] => '345'
// )
This matches your requirement exactly. The key values 'b' and 'c' remain unchanged because array_splice() respects the existing keys when removing elements.
Behavior with Multi-dimensional Arrays
The same logic applies to nested arrays. Consider a multi-dimensional array where the top-level keys are strings:
$array = [
'39' => [
'id' => '39',
'field_id' => '620'
],
'40' => [
'id' => '40',
'field_id' => '620',
'default_value' => 'rrr'
]
];
Calling array_splice($array, 0, 1) removes the entry with key '39' while preserving the key '40':
array_splice($array, 0, 1);
print_r($array);
Output:
Array (
['40'] => Array (
[id] => '40',
[field_id] => '620',
[default_value] => 'rrr'
)
)
The confusion often arises when inspecting the output in older PHP versions or certain IDEs that display arrays starting from index 0. However, array_splice() does not reset keys to 0, 1, 2... unless you explicitly ask for it via the optional "preserve keys" parameter (which is the default behavior). The key '40' remains '40'; it is just that after removal, '40' becomes the first element in the array.
Trade-offs and Pitfalls
While array_splice() solves the problem, keep these points in mind:
- Performance: For very large arrays, removing one element with
array_splice()still requires shifting all subsequent elements in memory. If you are doing this frequently in a tight loop, consider using an iterator or building a new array instead. - Side Effects:
array_splice()modifies the original array in place. If you need to keep the original data around, create a copy first:$copy = $array; array_splice($copy, 0, 1); - Return Value: The function returns the removed element(s). If you need that data, capture it:
$removed = array_splice($array, 0, 1);
When to Avoid foreach()
You mentioned not wanting to use foreach(). That is reasonable if your goal is a concise, single-call operation. Iterating with foreach() and building a new array works but adds verbosity and potential for off-by-one errors:
$newArray = [];
foreach ($array as $key => $value) {
if ($key !== '39') { // example removal condition
$newArray[$key] = $value;
}
}
Using array_splice() is cleaner and leverages built-in array functions designed for this exact purpose.
Conclusion
To remove the first element of an associative or multi-dimensional array without changing its keys, use array_splice($array, 0, 1). This approach preserves original keys, works with nested arrays, and avoids the automatic re-indexing behavior of array_shift().