Renumbering Array Keys in PHP: From Associative to Sequential Indexing
In PHP, arrays are technically maps of keys to values. While numeric indices starting at zero are convenient for iteration, there are scenariosâsuch as database queries, API responses, or legacy data structuresâwhere you need a sequential list starting at 1. The source material presents a specific case: an associative array with non-sequential keys [0], [1], and [2] containing objects that must be reindexed to start at [1] while preserving their order.
The most robust way to achieve this is by leveraging the array_values() function combined with manual offset adjustment. Here is the standard approach:
$newArray = array_values($oldArray);
$firstKey = array_key_first($newArray); // Returns 0
// Shift keys so the first element becomes 1
$shiftedKeys = range(1, count($newArray));
$newArray = array_combine($shiftedKeys, $newArray);
While this works, it relies on array_combine, which iterates through the array twice. A more performant and idiomatic solution involves array_shift() or simply iterating once to reconstruct the index map. However, a cleaner functional approach exists using array_map with a closure that ignores the original key and assigns a new one based on position:
$newArray = [];
$offset = 1;
foreach ($oldArray as $value) {
$newArray[$offset] = $value;
$offset++;
}
This method is explicit, readable, and avoids the overhead of creating intermediate index arrays. It works regardless of whether the original keys were sparse (e.g., [0], [5], [10]) or just out of order. The logic remains the same: you discard the old keys entirely and assign a new sequential integer based on the iteration count.
Why Not Just Use array_values()?
The built-in array_values() function strips all keys and reindexes them starting from 0. If your requirement is strictly to start at 1, you would have to manually add 1 to every key afterward, which adds unnecessary complexity. By using a simple loop or array_map, you handle the offset during the creation of the new array, keeping the operation atomic and clear.
Handling Sparse Keys and Performance
The example in the source material shows keys [0], [1], and [2]. These are technically contiguous, but often developers encounter arrays with gaps, such as ['key' => 'value'] mixed with numeric indices or missing numbers like [0], [2], [5].
When dealing with sparse keys, array_values() is still the safest first step to normalize the structure before applying your desired offset. For very large datasets, avoiding multiple passes over the data is critical. The loop-based approach shown above runs in a single pass (O(n) time complexity) and does not allocate extra memory for temporary index arrays, making it preferable over array_combine in high-performance contexts.
Preserving Value Types
It is important to note that this operation preserves the value type. Since your source array contains objects (Object with properties like title and linked), they are passed by reference in the loop or copied by value depending on PHP's internal handling, but the object references themselves remain intact. The keys change, but the content does not mutate unless explicitly modified within the loop body.
When to Use This Pattern
You might need this pattern when preparing data for JSON output where clients expect 1-based indexing (common in some legacy systems or specific regional formats), or when interfacing with SQL queries that require LIMIT 0, N logic mapped directly to row numbers starting at 1. In Laravel, while the framework handles most Eloquent collections elegantly, raw array manipulation still requires these explicit steps unless you use a collection method like values() combined with mapping.
If you are working within the Laravel ecosystem and need to manipulate arrays frequently, consider whether converting to a Collection first might offer cleaner syntax for chaining operations, though the underlying logic remains identical.
Ultimately, the choice between using array_values() followed by an offset shift or iterating directly depends on your specific performance constraints and code readability preferences. For most applications, the explicit loop is the most maintainable solution.
