The array_unique()
method will remove duplicate values from an array in PHP and is supported by PHP version 4 and later.
The array_unique()
method will accept an array
parameter whose duplicate will be removed from the array list and the filtered array returned. This duplicate will be removed using the flag, which was provided as the sorting method. If a duplicate is found in the array passed, it will be removed and one of it will be returned.
The keys of this array are not changed. When there are multiple elements, which are equal when compared, the key and value of the first equal element will be retained.
Note: We can only say that two values are equal if the elements being considered, that is
(string) $firstElement === (string) $secondElement
, have the same string form. If they are the same, then the first element will be used.
array_unique($array_value,$flags)
$array_value
: This is the array which we would want to remove duplicate values from, based on the flag provided.$flag
: The second parameters $flag
may be used to change the default sorting behavior of these values. The different options include the following.
SORT_REGULAR
: This compares items normally; that is, it won’t change types.SORT_NUMERIC
: This compares items numerically.SORT_STRING
: This compares items as strings.SORT_LOCALE_STRING
:
This compares items as strings, based on the current locale.This returns an array with the duplicate values removed.
Let’s take a look at the code example below.
<?php//duplicate value home in the below array$array_value = array("in" => "school", "market", "at" => "home", "party", "home");$output1 = array_unique($array_value);print_r($output1);//duplicate id 1 in the array fruit$fruits = array(1 => array("id"=>"3", "name"=>"apple", "price"=>"2090"),1 => array("id"=>"4", "name"=>"mango", "price"=>"3493"),2 => array("id"=>"3", "name"=>"pineapple", "price"=>"1390"),3 => "orange",3 => "orange",);$output2 = array_unique($fruits);print_r($output2);?>
array_unique
method to remove the duplicate and save the output.$fruits
, which has some duplicate elements. It is a nested array.array_unique
method to return unique contents of the variable $output2
. The arrays with index key 1
were both removed, because even though they’re duplicates, their values are not ===
, which is exactly the same as the strings. However, one of the duplicates of key index 3
was returned because the contained values are exactly the same.