Search code examples
phparraysequalsarray-column

How can I check and delete duplicate arrays?


how can I check and delete duplicate arrays?

Example:

$a = array(
   array(
      'id' => 1,
      'name' => 'test'
   ),
   // Next array is equal to first, then delete
   array(
      'id' => 1,
      'name' => 'test'
   ), 
   // Different array, then continue here
   array(
      'id' => 2,
      'name' => 'other'
   )
);

If the array is the same, then delete the duplicate and get only one array.


Solution

  • You can use a lookup table storing serialized arrays. If an array already exists in the lookup table, you have a duplicate and can splice out the key:

    $a = array(
       array(
          'id' => 1,
          'name' => 'test'
       ),
       array(
          'id' => 1,
          'name' => 'test'
       ), 
       array(
          'id' => 2,
          'name' => 'other'
       )
    );
    
    $seen = [];
    
    for ($i = count($a) - 1; $i >= 0; $i--) {
        if (array_key_exists(json_encode($a[$i]), $seen)) {
            array_splice($a, $i, 1);
        }
        else {
            $seen[json_encode($a[$i])] = 1;
        }
    }
    
    print_r($a);
    

    Output:

    Array
    (
        [0] => Array
            (
                [id] => 1
                [name] => test
            )
    
        [1] => Array
            (
                [id] => 2
                [name] => other
            )
    
    )
    

    Try it!