PHP » Arrays » array_unique()

Syntax:
array array_unique (array array)
array
Array for which duplicates should be removed.

Returns an array without duplicates.

The array_unique() function returns a copy of the input array with any duplicates removed. The keys will be preserved, i.e. arrays will not be reindexed. When duplicates are removed, the first key will be kept.

Examples

Code:
<pre>
<?php

$array1 = array("one", "one", "two", "two", "three", "three");

$array2 = array(
   "un" => "one",
   "un" => "one",
   "deux" => "two",
   "dos" => "two",
   "trois" => "three",
   "tres" => "three");


print_r(array_unique($array1));
print "<br>";
print_r(array_unique($array2));

?>
</pre>
Output:
Array
(
   [0] => one
   [2] => two
   [4] => three
)
Array
(
   [un] => one
   [deux] => two
   [trois] => three
)
Explanation:

array_unique() is used on two arrays, one numerically indexed, and one associative with translations from French and Spanish to the same English words. After using array_unique(), only half of the elements are left. Note what happened (or did not happen) to the keys.

See Also: