Filter array to have only unique values


/ Published in: PHP
Save to your folder(s)

Filter array to have only unique values


Copy this code and paste it in your HTML
  1. function arrayUnique($array, $preserveKeys = false)
  2. {
  3. // Unique Array for return
  4. $arrayRewrite = array();
  5. // Array with the md5 hashes
  6. $arrayHashes = array();
  7. foreach($array as $key => $item) {
  8. // Serialize the current element and create a md5 hash
  9. $hash = md5(serialize($item));
  10. // If the md5 didn't come up yet, add the element to
  11. // to arrayRewrite, otherwise drop it
  12. if (!isset($arrayHashes[$hash])) {
  13. // Save the current element hash
  14. $arrayHashes[$hash] = $hash;
  15. // Add element to the unique Array
  16. if ($preserveKeys) {
  17. $arrayRewrite[$key] = $item;
  18. } else {
  19. $arrayRewrite[] = $item;
  20. }
  21. }
  22. }
  23. return $arrayRewrite;
  24. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.