PHP Function Reference

PHP array_unique() Function



The PHP array_unique() function takes an input array and returns a new array without duplicate values. Please note that the keys are preserved while removing duplicates from an array.

Note: If multiple elements compare equal under the given flags, then the key and value of the first equal element is retained. Two elements are considered equal if their string representation are same i.e. $elem1 === (string) $elem2.

Syntax

array_unique(array, flags)

Parameters

array Required. Specify the input array.
flags Optional. Specify sorting type flags to modify the sorting behavior. Sorting type flags:
  • SORT_REGULAR - Default. Compare items normally.
  • SORT_NUMERIC - Compare items numerically.
  • SORT_STRING - Compare items as strings.
  • SORT_LOCALE_STRING - Compare items as strings, based on current locale.

Return Value

Returns the filtered array.

Exceptions

NA.

Example:

The example below shows the usage of array_unique() function.

<?php
$Arr = array(1, 2, 3, '2', '4');

//removing duplicates from the array
$result = array_unique($Arr);

//displaying the result
print_r($result);
?>

The output of the above code will be:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 4
)

Example:

Consider one more example where the array_unique() function is used with an associative array.

<?php
$Arr = array("a"=>"Red",
             "b"=>"Blue",
             "c"=>"Green",
             "d"=>"Red",
             "e"=>"Blue");

//removing duplicate entries from the array
$result = array_unique($Arr);

//displaying the result
print_r($result);
?>

The output of the above code will be:

Array
(
    [a] => Red
    [b] => Blue
    [c] => Green
)

❮ PHP Array Reference