PHP: remove duplicate elements from a multi-dimensional array

This post is over 3 years old, so please keep in mind that some of its content might not be relevant anymore.

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 representation
  • array_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!

One thought on “PHP: remove duplicate elements from a multi-dimensional array”

  1. Thank you for sharing your info. I truly appreciate your efforts and
    I am waiting for your further post thanks once again.

Leave a Reply

Your email address will not be published. Required fields are marked *