PHP array_unique() function is used to remove duplicate values from an array.
If there are multiple elements in the array with the same values, then the first appearing element will be kept, and all other occurrences of this element will be removed from the array.
Important points to know:
- The keys of array are preserved.
- array_unique() is not intended to work on multidimensional arrays.
Syntax
array_unique($array, [sortingType])
Parameters
array(required): It is an input array.
sortingType(optional): Specifying how to compare the array element. The following are some soringType flags.
- SORT_REGULAR – Compare items usually (don’t change types)
- SORT_NUMERIC – Compare items numerically
- SORT_STRING(Default) – Compare items as strings
- SORT_LOCAL_STRING – Compare items as strings based on the current locale.
Return value
It returns an array that contains unique elements.
Visual Representation
Example 1: How to Use array_unique() function
<?php
$singer = ["Drake","Justin","Selena","Drake","Rema"];
echo "Before apply unique: \n";
print_r($singer);
echo "After apply unique: \n";
print_r(array_unique($singer));
Output
Before apply unique:
Array
(
[0] => Drake
[1] => Justin
[2] => Selena
[3] => Drake
[4] => Rema
)
After apply unique:
Array
(
[0] => Drake
[1] => Justin
[2] => Selena
[4] => Rema
)
The output contains unique elements “Drake”, “Justin”, “Selena”, and “Rema”.
You can see that the keys of the input array are preserved.
Example 2: Using Associative Array
<?php
$name = ["a" => "krunal",
"b" => "krunal",
"c" => "ankit",
"d" => "Yuvi",
"e" => "rushabh"];
echo "Before apply unique: \n";
print_r($name);
$result = array_unique($name);
echo "After apply unique: \n";
print_r($result);
Output
Before apply unique:
Array
(
[a] => krunal
[b] => krunal
[c] => ankit
[d] => Yuvi
[e] => rushabh
)
After apply unique:
Array
(
[a] => krunal
[c] => ankit
[d] => Yuvi
[e] => rushabh
)
That’s it.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.
Thanks Brother, That Work (: