array_unique and then renumbering keys

array_unique and then renumbering keys

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

Stefan Bogdanescu

Founder & Senior Architect

The Hidden Cost of array_unique on Numeric Keys

When you chain array_unique() to a standard PHP array, the function behaves exactly as documented: it removes duplicate values while preserving the order of first occurrence. However, there is a subtle side effect that frequently catches developers off guard—the resulting keys are no longer consecutive. Instead, they become sparse, retaining their original indices from the source array.

In your specific example, array_unique correctly identifies and keeps the first instance of each date range. Yet, it leaves you with an array where keys jump from 0 to 4, then to 5, and finally to 7. While this technically satisfies the definition of a unique array, it often breaks downstream logic that assumes a sequential list, such as looping over items or passing data to JSON encoders expecting dense indices.

To fix this, you need to explicitly re-index the keys after deduplication. The most straightforward and efficient approach is to use array_values(). This function creates a new array containing all of the elements from the input array, but with numeric indices starting at zero and incrementing by one for each element.

Here is how you apply it:

$input = [
    0 => '15/11/2012 - 18/11/2012',
    1 => '15/11/2012 - 18/11/2012',
    4 => '19/12/2012 - 24/12/2012',
    5 => '24/12/2012 - 01/01/2013',
    7 => '16/01/2013 - 01/02/2013'
];

// Step 1: Remove duplicates
$unique = array_unique($input);

// Step 2: Re-index keys to be consecutive
$result = array_values($unique);

This combination is the standard idiom in PHP for this exact scenario. array_unique handles the filtering logic efficiently, while array_values handles the restructuring without copying the data twice or requiring manual loops.

Performance Considerations

It is worth noting that array_unique operates by comparing values against a hash table of seen items. If your array contains large strings or complex objects, this hashing process can be memory-intensive. However, for simple string comparisons like date ranges, the overhead is negligible.

The cost comes mainly from the two-step process: filtering first, then re-indexing. You could theoretically write a single loop that checks for duplicates and assigns new keys simultaneously. While this avoids creating the intermediate sparse array, it does not offer a significant performance gain in modern PHP versions because array_unique is already highly optimized in C. The readability of the two-step approach usually outweighs micro-optimization benefits here.

Trade-offs with Associative Arrays

Be cautious if your array keys are not numeric integers. If you pass an associative array to array_values(), it will re-index them as 0, 1, 2... regardless of their original string keys. This is exactly what you want when cleaning up a list, but it destroys the association between keys and values if those keys carried semantic meaning (e.g., user IDs).

In your case, since the data represents a timeline of events, consecutive integer keys are the desired state for iteration and serialization. If you need to maintain the original sparse keys for some reason—perhaps to preserve alignment with an external dataset—you would skip array_values() entirely, though this rarely makes sense after deduplication.

A Note on Laravel Collections

If you are working within the Laravel ecosystem, there is a cleaner alternative using the collection syntax available in https://laravelcompany.com. Collections wrap arrays and provide fluent interfaces that make these operations more readable. You can achieve the same result by filtering duplicates and then resetting keys:

$collection = collect($input)
    ->unique()
    ->values(); // equivalent to array_values()

The unique method removes duplicates based on value, and values returns a new collection with re-indexed keys. This pattern is often preferred in Laravel codebases for its readability, although the underlying implementation still relies on the same standard PHP functions.

Conclusion

The solution is simple but requires two distinct operations. First, filter the data to remove redundancy using array_unique. Second, normalize the structure to ensure consecutive indexing with array_values. Avoid trying to combine these into a single custom loop unless you have specific constraints preventing function calls; sticking to these built-in functions ensures your code remains fast, readable, and compatible across different PHP versions.

Our network