PHP’s array_unique() is great for removing duplicates from a flat array, but it chokes on multi-dimensional arrays. If you have nested data and need to remove duplicates, here’s a clean one-liner that does the job.
The trick: serialize, unique, unserialize
The idea is straightforward: flatten the array temporarily by serialising each element, let array_unique() do its thing on the flat list, then unserialise everything back to its original structure.
$uniqueArray = array_map("unserialize", array_unique(array_map("serialize", $array)));
Working from the inside out:
array_map("serialize", $array)— turns each nested element into a string representationarray_unique()— removes duplicate strings (which means duplicate nested structures)array_map("unserialize", ...)— restores each string back to its original PHP value
The result is a multi-dimensional array with all duplicate entries removed, regardless of how deep the nesting goes. You keep the original structure and no external libraries needed.
Hope it helps!