Remove duplicated elements of associative array in PHP

ID : 131401

viewed : 8

Tags : phparraysmultidimensional-arrayphp

Top 3 Answer for Remove duplicated elements of associative array in PHP

vote vote


Regardless what others are offering here, you are looking for a function called array_uniqueDocs. The important thing here is to set the second parameter to SORT_REGULAR and then the job is easy:

array_unique($result, SORT_REGULAR); 

The meaning of the SORT_REGULAR flag is:

compare items normally (don't change types)

And that is what you want. You want to compare arraysDocs here and do not change their type to string (which would have been the default if the parameter is not set).

array_unique does a strict comparison (=== in PHP), for arrays this means:

$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.

Output (Demo):

Array (     [0] => Array         (             [a] => 1             [b] => Hello         )      [1] => Array         (             [a] => 1             [b] => other         ) ) 
vote vote


First things first, you can not use plain array_unique for this problem because array_unique internally treats the array items as strings, which is why "Cannot convert Array to String" notices will appear when using array_unique for this.

So try this:

$result = array(     0=>array('a'=>1,'b'=>'Hello'),     1=>array('a'=>1,'b'=>'other'),     2=>array('a'=>1,'b'=>'other') );  $unique = array_map("unserialize", array_unique(array_map("serialize", $result)));  print_r($unique); 


Array (     [0] => Array         (             [a] => 1             [b] => Hello         )      [1] => Array         (             [a] => 1             [b] => other         )  ) 

Serialization is very handy for such problems.

If you feel that's too much magic for you, check out this blog post

function array_multi_unique($multiArray){    $uniqueArray = array();    foreach($multiArray as $subArray){      if(!in_array($subArray, $uniqueArray)){       $uniqueArray[] = $subArray;     }   }   return $uniqueArray; }  $unique = array_multi_unique($result);  print_r($unique); 

Ironically, in_array is working for arrays, where array_unique does not.

vote vote


Top 3 video Explaining Remove duplicated elements of associative array in PHP