PHP

Get Unique Values from a PHP Array

Discover how to efficiently remove duplicate values from a simple PHP array using `array_unique`, with options to preserve or reset array keys.

$numbers = [1, 2, 2, 3, 4, 4, 5, 1];
$uniqueNumbers = array_unique($numbers);
print_r($uniqueNumbers);
// Expected output: Array ( [0] => 1 [1] => 2 [3] => 3 [5] => 5 )

// Reset keys after getting unique values
$uniqueNumbersResetKeys = array_values(array_unique($numbers));
print_r($uniqueNumbersResetKeys);
// Expected output: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 5 )

$colors = ['red', 'green', 'blue', 'RED', 'green'];
// Case-insensitive unique values (requires a custom approach if not using flags for strict types)
$uniqueColorsCaseInsensitive = array_unique(array_map('strtolower', $colors));
print_r($uniqueColorsCaseInsensitive);
// Expected output: Array ( [0] => red [1] => green [2] => blue )
How it works: The `array_unique()` function removes duplicate values from an array. By default, it preserves the key of the first encountered value and discards subsequent duplicates. To get a numerically re-indexed array, `array_values()` can be used after `array_unique()`. For case-insensitive uniqueness, converting all string values to a common case (e.g., lowercase) before applying `array_unique()` is a common approach.

Need help integrating this into your project?

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

Hire DigitalCodeLabs