PHP array_unique() function

Example

Remove duplicate values from the array:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>

Run Example

Definition and Usage

The array_unique() function removes duplicate values from the array and returns the resulting array.

When several array elements have equal values, only the first element is retained, and the other elements are deleted.

The key names in the returned array remain unchanged.

Note:The retained array will keep the key name type of the first array item.

Syntax

array_unique(array)
Parameters Description
array Required. Specify the array.
sortingtype

Optional. Specify how to compare array elements/items. Possible values:

  • SORT_STRING - Default. Compare items as strings.
  • SORT_REGULAR - Sort items in regular order (Standard ASCII, without changing the type).
  • SORT_NUMERIC - Treat each item as a number.
  • SORT_LOCALE_STRING - Treat each item as a string, based on the current locale (can be changed by setlocale()).

Description

The array_unique() function first sorts the values as strings, then retains the first encountered key name for each value, and ignores all subsequent key names. This does not mean that the first occurrence of the same value in the unsorted array will retain its key name.

Technical Details

Return Value: Returns the filtered array.
PHP Version: 4.0.1+
Update Log:

In PHP 5.2.10,sortingtype The default value is changed back to SORT_STRING.

In PHP 5.2.9,sortingtype The default value is changed to SORT_REGULAR. In previous versions, the default value of sortingtype was SORT_STRING.