Remove duplicates from an array in PHP
In this post, we will see how to remove duplicates from an array in PHP. Two elements are considered equal if and only if the string representation is the same.
1. Removing duplicates using array_unique() function
The standard solution to remove duplicate values from an array is using the array_unique() function, which takes an array and returns a new array without duplicates and original order of keys preserved.
The following code demonstrates this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $arr = [1, 2, 3, 2, 4]; $distinct = array_unique($arr); print_r($distinct); /* Output: Array ( [0] => 1 [1] => 2 [2] => 3 [4] => 4 ) */ ?> |
For associative arrays, the key of the first equal element will be retained, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php $arr = array("a" => "green", "b" => "blue", "c" => "red", "d" => "green"); $distinct = array_unique($arr); print_r($distinct); /* Output: Array ( [a] => green [b] => blue [c] => red ) */ ?> |
For an array of different types, if the string representation of two elements is the same, the first element is used.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<?php $arr = array(1, "1", "2", 1, 2, "2"); $distinct = array_unique($arr); var_dump($distinct); /* Output: array(2) { [0]=> int(1) [2]=> string(1) "2" } */ ?> |
2. Find duplicates using array_diff_key() function
To find duplicates, you can use the array_diff_key() function which computes the difference of arrays using keys for comparison.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<?php $arr = [1, 2, 3, 2, 4]; $distinct = array_unique($arr); $duplicates = array_diff_key($arr, $distinct); print_r($duplicates); /* Output: Array ( [3] => 2 ) */ ?> |
That’s all about removing duplicates from an array in PHP.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)