0
0
PhpHow-ToBeginner · 3 min read

How to Remove Duplicates from Array in PHP Easily

To remove duplicates from an array in PHP, use the 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): array

array: 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.

php
array_unique(array $array, int $flags = SORT_STRING): array
💻

Example

This example shows how to remove duplicate values from an array of numbers and then reindex the array keys.

php
<?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);
?>
Output
Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
⚠️

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
<?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);
?>
Output
Array ( [a] => apple [b] => banana ) Array ( [0] => apple [1] => banana )
📊

Quick Reference

  • array_unique($array): Removes duplicates, preserves keys.
  • array_values($array): Reindexes array keys to sequential numbers.
  • Use SORT_NUMERIC flag for numeric comparison.
  • Works only on one-dimensional arrays.

Key Takeaways

Use array_unique() to remove duplicate values from an array in PHP.
Remember that array_unique() preserves original keys; use array_values() to reindex keys.
The default comparison is string-based; use flags like SORT_NUMERIC for numeric arrays.
array_unique() works only on one-dimensional arrays, not multidimensional ones.
Always test your array after removing duplicates to ensure keys and values are as expected.