PHP

Remove Duplicates and Re-index a Numeric Array

Learn how to efficiently remove duplicate values from a PHP numeric array and re-index it to ensure sequential keys after removal, improving array consistency.

<?php

$data = [1, 2, 2, 3, 4, 4, 5, 1];

// Remove duplicate values
$uniqueValues = array_unique($data);

// Re-index the array to have sequential keys starting from 0
$reindexedArray = array_values($uniqueValues);

print_r($reindexedArray);

// Output:
// Array
// (
//     [0] => 1
//     [1] => 2
//     [2] => 3
//     [3] => 4
//     [4] => 5
// )

?>
How it works: This snippet demonstrates a common pattern for cleaning up PHP arrays. `array_unique()` removes all duplicate values, but it preserves the original keys. To get a clean, sequentially indexed array (0, 1, 2...), `array_values()` is used immediately afterward to re-index the array. This is particularly useful when preparing data for display or further processing where non-sequential keys might cause issues.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs