Array Functions

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 SORT_STRING, this function build a new array by adding the unique elements which result in different numeric indexes.

In PHP 5.2.10 the default value of sort_flags changed back to SORT_STRING

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:

array_unique(array, sort_flags);

The following example shows the array_unique() function in action.

<?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:

  • SORT_STRING – Compare items as strings. Default value.
  • SORT_NUMERIC – Compare items numerically.
  • SORT_REGULAR – Compare items normally (don't change types).
  • SORT_LOCALE_STRING – Compare items as strings, based on the current locale.

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:

<?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.

<?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);
?>
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties