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!

How to run a system command in background from PHP

If you are at the command line and want a process to run in the background, you add an & at the end of the command:

sleep 10 && echo "Done!" &

The same approach works from PHP when you need to run a long process without making the user wait:

exec("tar czf /backup/site.tar.gz /var/www > /dev/null 2>&1 &");

The > /dev/null 2>&1 discards output so PHP doesn’t wait for it. The & sends the process to the background.

PHP functions compared

  • exec() — returns last line of output, does not block if output is redirected
  • shell_exec() — returns full output as a string
  • system() — outputs directly to the browser
  • passthru() — for binary output

Using nohup and PIDs

exec("nohup tar czf /backup/site.tar.gz /var/www > /dev/null 2>&1 & echo $!", $output);
$pid = $output[0];

nohup keeps the process alive after PHP exits. The PID lets you monitor or kill it later.

Enjoy!