Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_unique

Removes duplicate values from an array.

Available since: PHP 4

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
$flagsintHow 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, c

Notes

Values are compared loosely, as strings: the number 1 and the string '1' count as duplicates.

See also

Related recipes

In the tutorial

  • Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.

Thanks for reading!

Donate to the site — we work hard for you.