Prithviraj Mitra Prithviraj Mitra - 11 days ago 5
PHP Question

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.

Answer

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;