How can I remove duplicate values from a multi-dimensional array in PHP?
Example array:
Array ( [0] => Array ( [0] => abc [1] => def ) [1] => Array ( [0] => ghi [1] => jkl ) [2] => Array ( [0] => mno [1] => pql ) [3] => Array ( [0] => abc [1] => def ) [4] => Array ( [0] => ghi [1] => jkl ) [5] => Array ( [0] => mno [1] => pql ) )
The array_unique() function removes duplicate values from an array. If two or more array values are the same, the first appearance will be kept and the other will be removed.
To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.
A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays more than three levels deep are hard to manage for most people.
Here is another way. No intermediate variables are saved.
We used this to de-duplicate results from a variety of overlapping queries.
$input = array_map("unserialize", array_unique(array_map("serialize", $input)));
Since 5.2.9 you can use array_unique()
if you use the SORT_REGULAR
flag like so:
array_unique($array, SORT_REGULAR);
This makes the function compare elements for equality as if $a == $b
were being used, which is perfect for your case.
Output
Array ( [0] => Array ( [0] => abc [1] => def ) [1] => Array ( [0] => ghi [1] => jkl ) [2] => Array ( [0] => mno [1] => pql ) )
Keep in mind, though, that the documentation states:
array_unique()
is not intended to work on multi dimensional arrays.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With