I have two arrays with different size but the same element name. and i want to compare that two arrays to find different element.
$arr_1=array(array('name'=>'john','sex'=>'male','grade'=>'9'),array('name'=>'Smith','sex'=>'male','grade'=>'11'));
$arr_2=array(array('name'=>'john','sex'=>'male','grade'=>'9'),array('name'=>'Smith','sex'=>'male','grade'=>'11'),array('name'=>'Kelly','sex'=>'female','grade'=>'10'));
i want to find the different element between that two arrays and printout the result.
i want output like this
'name'=>'Kelly','sex'=>'female','grade'=>'10'
Use array_udiff instead of array_diff, check the demo
$arr_1=array(array('name'=>'john','sex'=>'male','grade'=>'9'),array('name'=>'Smith','sex'=>'male','grade'=>'11'));
$arr_2=array(array('name'=>'john','sex'=>'male','grade'=>'9'),array('name'=>'Smith','sex'=>'male','grade'=>'11'),array('name'=>'Kelly','sex'=>'female','grade'=>'10'));
function udiff($a, $b)
{
return ($name_diff = strcmp($a["name"],$b["name"])) ? $name_diff : (($sex_diff = strcmp($a["sex"],$b["sex"])) ? $sex_diff : (strcmp($a["grade"],$b["grade"])));
}
$arrdiff = array_udiff($arr_2, $arr_1, 'udiff');
print_r($arrdiff);
You can use php function array_diff()
.
Because you have nasted array, you can use like this.
Another way of doing it using array_diff and array_map.
<?php
$arr_1=array(array('name'=>'john','sex'=>'male','grade'=>'9'),array('name'=>'Smith','sex'=>'male','grade'=>'11'));
$arr_2=array(array('name'=>'john','sex'=>'male','grade'=>'9'),array('name'=>'Smith','sex'=>'male','grade'=>'11'),array('name'=>'Kelly','sex'=>'female','grade'=>'10'));
$c1 = array_map("customImplode",$arr_1);
$c2 = array_map("customImplode",$arr_2);
function customImplode($data){
return implode("|",$data);
}
function customExplode($data){
return explode("|",$data);
}
$result = array_map("customExplode",array_unique(array_merge(array_diff($c1,$c2),array_diff($c2,$c1))));
echo "<pre>";
print_r($result);
Demo: https://3v4l.org/ULtdp
Note that the comparison here is case sensitive.