PHP Reference ยท Array Functions
PHP array_unique() function
Reference for PHP array_unique(): remove duplicate values, understand the loose string comparison and the flags, and how keys are kept or reindexed.
array_unique() returns a copy of an array with duplicate values removed. When several elements are equal, the first one is kept, together with its key, and the later ones are dropped.
Because keys are preserved, the result may have gaps in its numbering. Equality is decided by comparing the values as strings by default, which has consequences for numbers, booleans and null.
<?php print_r(array_unique([3, 1, 3, 2, 1])); // [0 => 3, 1 => 1, 3 => 2]
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
array_unique(array $array, int $flags = SORT_STRING): array
| Name | Description |
|---|---|
$array |
The input array. It is not modified. |
$flags |
How to compare values: SORT_STRING (default, compare as strings), SORT_REGULAR (compare with ==), SORT_NUMERIC (compare as numbers) or SORT_LOCALE_STRING (compare as strings using the current locale). |
Return value: a new array without duplicates, keeping the original keys of the first occurrences.
Usage notes
- First occurrence wins, along with its key. Call
array_values()when you want a gapless list. - Default comparison is by string, so
1and"1"are duplicates, andnull,falseand""are duplicates of each other. - Arrays as elements cannot be converted to strings, so use
SORT_REGULAR; with the default flag they trigger an "Array to string conversion" warning. - Case and whitespace count. Normalize first with
array_map()andstrtolower()ortrim()if you want "Apple" and "apple" merged. - Speed: older versions sorted internally; for large lists of strings or integers, flipping with
array_flip()and taking the keys is a fast alternative that also keeps one copy of each value. - Objects: with
SORT_REGULAR, objects are compared with==, which compares their properties. - Counting duplicates instead of removing them is the job of
array_count_values().