I was recently working on a PHP application for a Client where I was faced with a Multi-Dimensional Array filled with duplicate entries and a lot of unusable data.

What I needed was to extract all the unique elements of the Array so I had some clean data to work with. 
I googled ‘PHP unique array’ and found what I thought I was looking for.

Unfortunately I found that the array_unique function only works on Integers and Strings! Luckily for me, someone had the exact same issue and wrote a custom function to extract unique elements on Multi-Dimensional Arrays:

function super_unique($array)
  $result = array_map("unserialize", array_unique(array_map("serialize", $array)));
  foreach ($result as $key => $value)
    if ( is_array($value) )
      $result[$key] = super_unique($value);
  return $result;

Using this function, I was able to filter my Multi-Dimensional Array to return only unique elements and work with the clean data I needed to finish the application.

Hopefully this helps some other developers out there!

You may also like

Newsletter sign up

Every couple of months we send out an update on what's been happening around our office and the web. Sign up and see what you think. And of course, we never spam.