PHP array_unique() Function
Topic: PHP Array ReferencePrev|Next
Description
The array_unique()
function removes duplicate values from an array.
If multiple values are found equal, the first value and its key will be kept and others will be removed.
The following table summarizes the technical details of this function.
Return Value: | Returns a new array without duplicate values. |
---|---|
Changelog: |
Since PHP 7.2.0 if sort_flags is In PHP 5.2.10 the default value of sort_flags changed back to In PHP 5.2.9 the default value of sort_flags changed to
SORT_REGULAR from SORT_STRING |
Version: | PHP 4.0.1+ |
Syntax
The basic syntax of the array_unique()
function is given with:
The following example shows the array_unique()
function in action.
Example
Run this code »<?php
// Sample array
$numbers = array(1, 2, 4, 5, 2, 5, 7, 2, 10);
// Removing the duplicate values from numbers array
$result = array_unique($numbers);
print_r($result);
?>
Parameters
The array_unique()
function accepts the following parameters.
Parameter | Description |
---|---|
array | Required. Specifies the array to work on. |
sort_flags |
Optional. Specifies how array items should be compared. Possible values are:
|
More Examples
Here're some more examples showing how array_unique()
function actually works:
The following example demonstrates how to get unique values from the associative arrays:
Example
Run this code »<?php
// Sample array
$input = array("foo"=>"hello", "bar"=>"world", "baz"=>"hello");
// Removing the duplicate values from input array
$result = array_unique($input);
print_r($result);
?>
The following example shows how this function works on array having duplicate values of mixed types.
Example
Run this code »<?php
// Sample array
$input = array(2, 4, "4", 5, "3", 4, 3, "3");
// Removing the duplicate values from input array
$result = array_unique($input);
print_r($result);
?>