Home >>PHP Array Functions >PHP array_unique() Function

PHP array_unique() Function

PHP array_unique() Function

PHP array_unique() function is used to remove the duplicate values from any given input array. If the array has multiple elements with same values then the first element present in the array will be kept and all other occurrences of that element will be removed from that array.

Syntax:

array_unique(array, sorttype);

Parameter Values

Parameter Description
array This is a required parameter. This parameter defines the given array.
sorttype This is an optional parameter. This parameter defines how to compare the array elements.

Here is an example of array_unique() function in PHP:

<html>
<body>
<pre>
<?php
$x=array("a","v","s","a","f","s","t","c","x","k","a","x","d");
print_r(array_unique($x));
?>
</pre>
</body>
</html>
Output:
Array
(
    [0] => a
    [1] => v
    [2] => s
    [4] => f
    [6] => t
    [7] => c
    [8] => x
    [9] => k
    [12] => d
)

Example 2:

<html>
<body>
<pre>
<?php
for($i=0;$i<=10;$i++)
{
$x[]=rand(0,9);
}
echo "Original Elements:<br> ";
print_r($x);
echo "Unique Elements:<br> ";
print_r(array_unique($x,SORT_NUMERIC));
?>
</pre>
</body>
</html>
Output:
Original Elements:
 Array
(
    [0] => 6
    [1] => 3
    [2] => 5
    [3] => 3
    [4] => 3
    [5] => 5
    [6] => 7
    [7] => 3
    [8] => 3
    [9] => 7
    [10] => 3
)
Unique Elements:
 Array
(
    [0] => 6
    [1] => 3
    [2] => 5
    [6] => 7
)

No Sidebar ads