How to Remove Duplicates from Array in PHP Easily
array_unique() function which returns a new array without repeated values. This function preserves the original keys unless you reindex the array with array_values().Syntax
The basic syntax to remove duplicates from an array is:
array_unique(array $array, int $flags = SORT_STRING): arrayarray: The input array to filter.
flags: Optional, defines how to compare values (e.g., SORT_STRING, SORT_NUMERIC).
The function returns a new array with duplicates removed, preserving the first occurrence of each value.
array_unique(array $array, int $flags = SORT_STRING): arrayExample
This example shows how to remove duplicate values from an array of numbers and then reindex the array keys.
<?php $numbers = [1, 2, 2, 3, 4, 4, 5]; $uniqueNumbers = array_unique($numbers); // Reindex keys to have sequential indexes $uniqueNumbers = array_values($uniqueNumbers); print_r($uniqueNumbers); ?>
Common Pitfalls
1. Keys are preserved by default: array_unique() keeps the original keys, which can cause unexpected gaps in indexes.
2. Type comparison: The default SORT_STRING flag compares values as strings, which may cause unexpected results with numbers.
3. Multidimensional arrays: array_unique() works only on one-dimensional arrays.
Always reindex the array with array_values() if you want clean numeric keys.
<?php // Wrong: keys preserved $fruits = ['a' => 'apple', 'b' => 'banana', 'c' => 'apple']; $uniqueFruits = array_unique($fruits); print_r($uniqueFruits); // Right: reindex keys $uniqueFruits = array_values(array_unique($fruits)); print_r($uniqueFruits); ?>
Quick Reference
array_unique($array): Removes duplicates, preserves keys.array_values($array): Reindexes array keys to sequential numbers.- Use
SORT_NUMERICflag for numeric comparison. - Works only on one-dimensional arrays.
Key Takeaways
array_unique() to remove duplicate values from an array in PHP.array_unique() preserves original keys; use array_values() to reindex keys.SORT_NUMERIC for numeric arrays.array_unique() works only on one-dimensional arrays, not multidimensional ones.