Re-indexing Arrays After Removal in PHP
You often encounter scenarios where you need to strip specific elements from an array and ensure the remaining items retain a contiguous numeric index starting from zero. In your specific example, you have an original array $foo containing ['whatever', 'foo', 'bar']. You want to remove the first element ('whatever') so that 'foo' shifts to index [0] and 'bar' shifts to index [1], resulting in $foo2.
This is a common requirement when manipulating data structures where the logical order of elements matters, but the physical indices must be dense. PHP provides several methods to achieve this, each with distinct performance characteristics and use cases.
The array_splice() Approach
The most robust and direct solution for this specific problem is the built-in array_splice() function. Unlike simple array shifting functions that only move elements forward, array_splice allows you to remove a range of elements and optionally re-index the result.
To replicate your desired transformation, you can slice off the first element. The function signature accepts the offset where cutting begins, the length of the section to remove, and an optional replacement array. To simply remove the first item and re-index the rest:
$foo = ['whatever', 'foo', 'bar'];
// Remove 1 element starting at index 0
array_splice($foo, 0, 1);
print_r($foo);
// Output: Array ( [0] => foo [1] => bar )
The key here is that array_splice automatically re-indexes the remaining elements. If you needed to replace the removed element with something else, you could pass a new value in the third argument. For instance, removing one element and replacing it with 'new' would yield ['new', 'bar'].
Using array_filter() for Complex Logic
If your removal criteria are based on values rather than strict indices, array_filter() combined with array_values() is a viable pattern. While array_splice is optimized for positional manipulation, array_filter iterates through the array to test a condition.
$foo = ['whatever', 'foo', 'bar'];
// Remove elements equal to 'whatever' and re-index
$foo2 = array_values(array_filter($foo, function ($value) {
return $value !== 'whatever';
}));
print_r($foo2);
// Output: Array ( [0] => foo [1] => bar )
Note the critical use of array_values(). Without it, array_filter preserves the original keys. If your array had sparse indices or non-numeric keys initially, they would remain intact after filtering. Re-indexing is mandatory to restore the dense numeric sequence you expect in most web applications.
Performance Considerations and Trade-offs
When deciding between these methods, consider the size of the dataset and the complexity of the removal logic. array_splice operates on a specific range and is generally faster for positional operations because it deals with memory blocks directly. It handles the re-indexing internally without requiring an extra pass over the array keys.
Conversely, array_filter creates an intermediate array based on your callback condition before array_values has to copy those values into new keys. This double-pass approach adds overhead for large datasets. If you are stripping many elements at once or working with high-performance requirements, prefer array_splice for positional removals.
Common Pitfalls
A frequent mistake developers make is assuming that removing an element automatically re-indexes the array. Simple assignment like $foo = [0] => 'foo' or even unset($foo[0]) leaves behind empty slots if the array was not sparse to begin with, or creates gaps if you are working within larger associative structures.
Always verify the output type. If your array contains mixed data types and keys, removing an element might leave string keys intact if not handled carefully. For purely numeric arrays requiring dense indexing, array_splice is the safest bet as it guarantees a contiguous 0-based index structure immediately after execution.
For developers working within the Laravel ecosystem, managing collections often involves similar logic. While native PHP functions like array_splice work fine with raw arrays, Laravel's collection facade offers methods like forPage, skip, and take that abstract this underlying array manipulation into fluent interfaces. Understanding the native behavior helps when debugging why a collection operation didn't behave as expected.
