Search code examples
phparraysdistinct-values

More elegant way of getting array with distinct values


I have this array:

$array[] = [
      'a' => $a,
      'b' => $b,
];

The array contains of let's say 10 entries, $a can be in there with the same value many times and I need only one of those entries for a db insert.

I can't manage to get array_unique working as it throws

 array to string conversion

error when trying to use it like

 $result = array_unique($array);

I now made a little foreach loop that feels just wrong to do so:

    $z = [];
    foreach ($array as $x) {

        if (@!in_array($x['a'],$z)) {
            $z[] = $x['a'];
        }
    }

and I use $z for the insert thereafter.

Can someone point me in the right direction of how to distinct my array values?


Solution

  • This should work for you:

    ($result = array_unique($array); this didn't worked, because you have a multidimensional array!)

    <?php
    
    
        //Example data
        $array[] = [
              'a' => 1,
              'b' => 1,
              'c' => 1,
              'd' => 2,
              'e' => 2,
    
        ];
    
        $array = array_map("array_unique", $array);
        print_r($array);
    
    ?>
    

    Output:

    Array ( [0] => Array ( [a] => 1 [d] => 2 ) )