I have this issue with multidimensional arrays.
Given the following multidimensional array:
Array(
[0] => Array("a", "b", "c")
[1] => Array("x", "y", "z")
[2] => Array("a", "b", "c")
[3] => Array("a", "b", "c")
[4] => Array("a", "x", "z")
)
I want to check its values and find duplicates (i.e. keys 0, 2 and 3) leaving just one key - value pair deleting the others, resulting in somthing like this:
Array(
[0] => Array("a", "b", "c")
[1] => Array("x", "y", "z")
[2] => Array("a", "x", "z")
)
How can I do that??
To check using array_unique on multidimensional arrays, you need to flatten it out like so, using implode.
Hope this is helpful, took sometime to get it.
You can go smart with serialization for comparison of arrays.
Have fun
This will remove duplicate items from your array using
array_unique()
:You can simply do it using in_array()
which will get you something like
This is a more efficient1 solution (log n + n instead of quadratic) but it relies on a total order between all the elements of the array, which you may not have (e.g. if the inner arrays have objects).
1 More efficient than using
in_array
. Turns outarray_unique
actually uses this algorithm, so it has the same shortcomings.