PHP array_unique() Function
The PHP array_unique() function removes duplicate values from an array, preserving the first occurrence of each value and reindexing the array with keys preserved. It’s useful for filtering out redundant data and ensuring a collection of unique elements within an array.
Syntax
array array_unique($array , $sort_flags)
Note: The keys of the array are preserved. That is, the keys of the not-removed elements of the input array will be the same in the output array.
Parameters
: This function accepts two parameters out of which one is mandatory and the other is optional. Both of these parameters are described below:
- $array: This parameter is mandatory to be supplied and it specifies the input array from which we want to remove duplicates.
- $sort_flags: This is optional parameter. This parameter $sort_flags may be used to modify the sorting behavior using these values:
- SORT_REGULAR: This is the default value of the parameter $sort_flags. This value tells the function to compare items normally (don’t change types).
- SORT_NUMERIC: This value tells the function to compare items numerically.
- SORT_STRING: This value tells the function to compare items as strings.
- SORT_LOCALE_STRING: This value tells the function to compare items as strings, based on the current locale.
Return Value: The array_unique() function returns the filtered array after removing all duplicates from the array.
Below programs illustrate the array_unique() function in PHP:
Example : In this example we removes duplicate values from the array a using array_unique() and prints the result.
<?php
// Input Array
$a=array("red", "green", "red", "blue");
// Array after removing duplicates
print_r(array_unique($a));
?>
Output
Array ( [0] => red [1] => green [3] => blue )
Example 2: In this example we removes duplicate values from the associative array arr using array_unique() and prints the result.
<?php
// Input array
$arr = array("a"=>"MH", "b"=>"JK", "c"=>"JK", "d"=>"OR");
// Array after removing duplicates
print_r(array_unique($arr));
?>
Output
Array ( [a] => MH [b] => JK [d] => OR )
PHP array_unique() Function – FAQs
Does array_unique() preserve array keys?
Yes, array_unique() preserves the keys of the first occurrences of values, but it reindexes numeric keys.
Can array_unique() handle multidimensional arrays?
No, array_unique() works only on one-dimensional arrays. It doesn’t compare nested arrays.
How does array_unique() compare values?
By default, it uses string comparison (SORT_STRING). You can change this using the optional sorting flag.
What are the optional flags for array_unique()?
Flags include SORT_REGULAR, SORT_NUMERIC, SORT_STRING, and SORT_LOCALE_STRING for different comparison types.
Does array_unique() affect the original array?
No, it returns a new array without modifying the original array.