Unique items in a multidimensional array in PHP

I just found this in the PHP documentation and thought it was neat enough to warrant a blog post.

array_unique() works fine for a single dimensional array, but falls down on multidimensional arrays because it relies on string comparisons. When it compares entries in a multidimensional array, it simply sees ‘Array’ === ‘Array’ and returns true. This means everything will appear to be the same, and you’ll only get one thing in your result set.

Steve in the comments for the array_unique function comes up with a novel solution. Store every result with a key based upon the md5 hash of the array item. This means if two items are the same, they will be stored under the same key, overwriting each other and making sure there’s only one of each. Really elegant.

Here’s how…

$unique = array();

foreach($my_duplicate_array as $entry) {
   $unique[md5(serialize($entry))] = $entry;
}

Sweet.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*