array_unique
Removes duplicate values from an array.
Available since: PHP 4
Syntax
array_unique(array $array, int $flags = SORT_STRING): arrayParameters
| Parameter | Type | Description |
|---|---|---|
| $array | array | The source array. |
| $flags | int | How values are compared. By default they are compared as strings. |
Return value
arrayThe array without duplicates. The first occurrence of each value is kept, and keys are preserved.
Examples
The keys of the remaining elements are preserved:
<?php
print_r(array_unique([1, 2, 2, 3, 1]));Output:
Array
(
[0] => 1
[1] => 2
[3] => 3
)A plain list without duplicates:
<?php
echo implode(', ', array_values(array_unique(['b', 'a', 'b', 'c', 'a'])));Output:
b, a, cNotes
Values are compared loosely, as strings: the number 1 and the string '1' count as duplicates.
See also
- array_filter — Keeps the array elements that pass a test.
Related recipes
In the tutorial
- Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.