PHP array_unique() 函数

实例

移除数组中重复的值:

<?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 maintain 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 each item in regular order (Standard ASCII, do not change type).
  • SORT_NUMERIC - Treat each item as a number.
  • SORT_LOCALE_STRING - Treat each item as a string, based on the current locale setting (can be changed by setlocale()).

Description

array_unique() 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 the key name.

Technical Details

Return Value: Return 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 Change the default value to SORT_REGULAR. In previous versions, the default value of sortingtype was SORT_STRING.