Menu Home

array_unique

osbo.com | PHP | Functions | array_unique

Removes duplicate values from an array

Syntax

array_unique ( array $array [, int $sort_flags = SORT_STRING ] ) : array

Parameters

array

The input array.

sort_flags

The optional second parameter sort_flags may be used to modify the sorting behavior using these values:

SORT_REGULAR compare items normally (don't change types)
SORT_NUMERIC compare items numerically
SORT_STRING compare items as strings
SORT_LOCALE_STRING compare items as strings, based on the current locale

Return

Returns the filtered array.

Examples

array

<?

$array = array("a" => "green", "red", "b" => "green", "blue", "red", "4", 4, "3", 3);

$return = array_unique($array);

print_r($return);

?>
Array
(
    [a] => green
    [0] => red
    [1] => blue
    [3] => 4
    [5] => 3
)

flags | SORT_REGULAR

<?

$array = array("a" => "green", "red", "b" => "green", "blue", "red", "4", 4, "3", 3);
$flags = SORT_REGULAR;

$return = array_unique($array, $flags);

print_r($return);

?>
Array
(
    [a] => green
    [0] => red
    [1] => blue
    [3] => 4
    [4] => 4
    [5] => 3
    [6] => 3
)

flags | SORT_NUMERIC

<?

$array = array("a" => "green", "red", "b" => "green", "blue", "red", "4", 4, "3", 3);
$flags = SORT_NUMERIC;

$return = array_unique($array, $flags);

print_r($return);

?>
Array
(
    [a] => green
    [3] => 4
    [5] => 3
)

flags | SORT_STRING

<?

$array = array("a" => "green", "red", "b" => "green", "blue", "red", "4", 4, "3", 3);
$flags = SORT_STRING;

$return = array_unique($array, $flags);

print_r($return);

?>
Array
(
    [a] => green
    [0] => red
    [1] => blue
    [3] => 4
    [5] => 3
)

flags | SORT_LOCALE_STRING

<?

$category = LC_ALL;
$locale = "en_US";

setlocale($category, $locale);

$array = array("a" => "green", "red", "b" => "green", "blue", "red", "4", 4, "3", 3);
$flags = SORT_LOCALE_STRING;

$return = array_unique($array, $flags);

print_r($return);

?>
Array
(
    [a] => green
    [0] => red
    [1] => blue
    [3] => 4
    [5] => 3
)

PHP