Prithviraj Mitra
Prithviraj Mitra

Reputation: 11812

Remove duplicate keys from both arrays using php

I want to remove duplicate keys from both arrays.

My code is

$arr1[22068] = array('ID' => 22068);
$arr1[22067] = array('ID' => 22067);
$arr2[22068] = array('ID' => 22068);
$arr2[22066] = array('ID' => 22066);

$arr = array_diff($arr1, $arr2);

var_dump($arr); //It outputs null.

The final array should look like this--

$arr[22066] = array('ID' => 22066);
$arr[22067] = array('ID' => 22067);

Any help is highly appreciated.

Upvotes: 0

Views: 54

Answers (2)

Patrick
Patrick

Reputation: 213

array_diff_key() is what you want.

$arr1[22068] = array('ID' => 22068);
$arr1[22067] = array('ID' => 22067);
$arr2[22068] = array('ID' => 22068);
$arr2[22066] = array('ID' => 22066);

// Get elements of array 1 which are not present in array 2
$unique_1 = array_diff_key($arr1, $arr2);

// Get elements of array 2 which are not present in array 1
$unique_2 = array_diff_key($arr2, $arr1);

// Merge unique values
$unique = $unique_1 + $unique_2;

Upvotes: 2

dpp
dpp

Reputation: 496

So array_diff will give you what's different in array1 vs array2, and will NOT work on multi-dimensional arrays. You can switch to array_key_diff, however, you'll run into a similar issue:

$arr1[22068] = array('ID' => 22068);
$arr1[22067] = array('ID' => 22067);
$arr2[22068] = array('ID' => 22068);
$arr2[22066] = array('ID' => 22066);

$arr = array_diff_key($arr1, $arr2);

var_dump($arr); //It outputs array(1) {[22067]=> array(1) { ["ID"]=> int(22067) } }

I'm not aware of a "magic" solution with the differences, however, you do have options, you can take the code above and add an extra line for:

$arr2 = array_diff_key($arr2, $arr1);
var_dump($arr2)

then merge $arr and $arr2, or you can just write a loop going through and comparing each item. Depending on size, scope, readability, etc will depend on the actual set

Upvotes: 1

Related Questions