How to Use array_unique in PHP: Remove Duplicate Values Easily
Use the
array_unique function in PHP to remove duplicate values from an array. It returns a new array with only unique values, preserving the original keys.Syntax
The array_unique function takes an array as input and returns a new array with duplicate values removed. It has an optional second parameter to specify how duplicates are compared.
array_unique(array $array, int $flags = SORT_STRING): array- $array: The input array to filter.
- $flags: Optional. Defines the comparison type (e.g.,
SORT_STRING,SORT_NUMERIC,SORT_REGULAR).
php
array_unique(array $array, int $flags = SORT_STRING): arrayExample
This example shows how to use array_unique to remove duplicate values from an array of fruits. The function returns a new array with only unique fruits, preserving the original keys.
php
<?php $fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'grape']; $uniqueFruits = array_unique($fruits); print_r($uniqueFruits); ?>
Output
Array
(
[0] => apple
[1] => banana
[3] => orange
[5] => grape
)
Common Pitfalls
One common mistake is expecting array_unique to reindex the array keys. It preserves original keys, which can cause unexpected results if you rely on sequential keys. To fix this, use array_values to reindex the array after removing duplicates.
Another pitfall is misunderstanding the $flags parameter, which affects how values are compared (string vs numeric).
php
<?php // Wrong: expecting keys to be reindexed $numbers = [1, 2, 2, 3]; $uniqueNumbers = array_unique($numbers); print_r($uniqueNumbers); // keys are 0,1,3 // Right: reindex keys after unique $uniqueNumbersReindexed = array_values(array_unique($numbers)); print_r($uniqueNumbersReindexed); // keys are 0,1,2 ?>
Output
Array
(
[0] => 1
[1] => 2
[3] => 3
)
Array
(
[0] => 1
[1] => 2
[2] => 3
)
Quick Reference
| Parameter | Description |
|---|---|
| $array | The input array to remove duplicates from. |
| $flags | Optional. Comparison type: SORT_STRING (default), SORT_NUMERIC, SORT_REGULAR. |
| Return | A new array with duplicate values removed, original keys preserved. |
Key Takeaways
Use array_unique to remove duplicate values from an array while preserving keys.
Remember array_unique does not reindex keys; use array_values to reset keys if needed.
The optional flags parameter controls how values are compared for uniqueness.
array_unique works on values only, not keys.
Always test output to understand how keys and values are handled.