Compare 2 arrays after removing keys that don't exist in both using array functions
I have 2 arrays a and b that may or may not have similar values.
$a = array('id' => 1, 'name' => 'John Doe', 'age' => 35);
$b = array('name' => 'John Doe', 'age' => 35);
I need to check if the keys that are in both arrays contain the same values or are not using the array functions themselves. Please help me.
NB: Array $ a is always the parent array. If any key needs to be popped it will only be from $ a.
source to share
You can use the following comparison based on array_intersect_assoc
:
$b == array_intersect_assoc($a, $b)
This will be true
when all key / value pairs $b
are found in $a
, false
otherwise.
source to share
Use this code:
Usage: array_diff_key
Remove duplicate key:
<?php
$a = array('id' => 1, 'name' => 'John Doe', 'age' => 35);
$b = array('name' => 'John Doe', 'age' => 35);
$c = array_diff_key($a, $b);
print_r($c); //Array ( [id] => 1 )
?>
Get a duplicate:
Usage: array_intersect_key
<?php
function array_duplicate_keys() {
$arrays = func_get_args();
$count = count($arrays);
$dupes = array();
// Stick all your arrays in $arrays first, then:
for ($i = 0; $i < $count; $i++) {
for ($j = $i+1; $j < $count; $j++) {
$dupes += array_intersect_key($arrays[$i], $arrays[$j]);
}
}
return array_keys($dupes);
}
print_r(array_duplicate_keys($a, $b)); //Array ( [0] => name [1] => age )
?>
Get duplicate key and value:
<?php
function get_keys_for_duplicate_values($my_arr, $clean = false) {
if ($clean) {
return array_unique($my_arr);
}
$dups = $new_arr = array();
foreach ($my_arr as $key => $val) {
if (!isset($new_arr[$val])) {
$new_arr[$val] = $key;
} else {
if (isset($dups[$val])) {
$dups[$val][] = $key;
} else {
$dups[$val] = array($key);
}
}
}
return $dups;
}
print_r(get_keys_for_duplicate_values($a, $b));
//Array ( [id] => 1 [name] => John Doe [age] => 35 )
?>
source to share
If $b
may have keys not present in $a
, you can use array_intersect_key two times, arguments in reverse order, and check if both results are the same:
$ab = array_intersect_key($a, $b);
$ba = array_intersect_key($b, $a);
$allValuesEqual = ($ab == $ba);
source to share
use this: "it compares both key and value"
$result=array_diff_assoc($a1,$a2); //<-Compare both key and value, gives new array
Example:
$a1=array("a"=>"red","b"=>"green","c"=>"blue");
$a2=array("a"=>"red","c"=>"blue","b"=>"pink");
$result=array_diff_assoc($a1,$a2);
print_r($result);
//result will be
Array ( [b] => green )
source to share