PHP reindex array?

PHP reindex array?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

PHP reindex array?

When you use unset() on specific keys in a PHP array, the resulting structure retains its original integer indices, leaving behind "holes." Your example illustrates this perfectly: an array that logically should contain four items now occupies indices 0, 1, 3, and 4 because index 2 was removed. While this behavior is consistent with how PHP handles sparse arrays, it often breaks logic that relies on sequential iteration or expects contiguous data structures.

The standard solution to restore a dense, zero-indexed sequence is the array_values() function. This built-in utility reconstructs the array by reindexing all elements using new integer keys starting from 0. It effectively discards the old keys and assigns fresh ones based on the order of the remaining elements.

$myarray = [
    0 => 'a->1',
    1 => 'a-7 b->3',
    // Index 2 is missing
    3 => 'a-8 b->6',
    4 => 'a-3 b->2'
];

$reindexed = array_values($myarray);

print_r($reindexed);

After running array_values(), $reindexed will contain keys 0 through 3 with the original values intact. This is the idiomatic approach in PHP because it explicitly signals an intent to treat the collection as a simple list of values rather than a map where specific keys might hold special meaning.

However, simply calling array_values() does not always solve the underlying problem. If your application logic depends on the data being associative or if you need to preserve the relationship between indices and specific identifiers, blindly reindexing can introduce bugs. For instance, if you are building a dataset for JSON output where the keys represent years (e.g., ['2020' => ...]) or IDs, converting those to 0, 1, 2 will break any downstream code expecting to access data via $data['2020'].

In modern Laravel projects, you might also encounter this situation when manipulating Eloquent collections. Since Laravel's Collection class wraps native arrays, it inherits the behavior of array_values(). You can chain this method directly onto a collection instance:

use Illuminate\Support\Collection;

$collections = Collection::make($myarray);
$reshuffled = $collections->values()->all();

The values() accessor on the Collection class is essentially a fluent interface wrapper around array_values(). This pattern keeps your code readable while maintaining type safety within the Laravel ecosystem. If you are using PHP 8.1 or later, you have additional options involving iterator classes, but array_values() remains the most performant and universally compatible choice for simple reindexing tasks.

There is a subtle performance consideration when dealing with massive datasets. While array_values() operates in linear time $O(n)$, creating a new array object every time you call it can lead to memory churn if done excessively inside tight loops. In high-throughput scenarios, it is often better to perform the reindexing once at the boundary of your data processing pipeline rather than repeatedly during intermediate steps.

Another common pitfall is confusing array_values() with array_combine(). If you have two arrays—one containing keys and one containing values—and you want to ensure they are synchronized without losing data, array_combine might seem like a viable alternative. However, array_combine requires both arrays to be the same length; if your "holes" represent missing data rather than just skipped indices, forcing them into a new associative structure could result in lost information or index mismatches.

Finally, keep in mind that reindexing changes the internal hash table of the array. If you have used array_rand() previously to generate random keys based on the current sparse structure, those random numbers will no longer be valid after reindexing. Always ensure that any logic relying on specific integer indices is updated or removed before calling array_values().

For developers working with legacy codebases where dense arrays are expected but sparse structures exist due to previous unset operations, array_values() is the definitive tool for normalization. It ensures that your data structure aligns with standard array assumptions, preventing subtle bugs caused by off-by-one errors or unexpected key collisions.

Our network