Reputation: 759
I have two arrays:
$a = [
36 => 7,
38 => 9,
41 => 12,
42 => 5
];
$b = [
38 => 9,
41 => 9,
42 => 5
];
Array a
has one extra key[36]
and array b
has a different value for key[41]
.
How do i set a key in a
to equal 0
if it is not in b
and then how do i update a key in a
if it has a different value in b
and how do i add new keys to a
if it is in b
and not in a
?
For now i've made this code:
foreach($a as $key => $value){
if(array_key_exists($key, $b) && $value != $b[$key]){
$a[$key] = $b[$key];
} else{
$a[$key] = 0;
}
}
if($diff = array_diff_key($b, $a)){
foreach($diff as $key => $value){
$a[$key] = $value;
}
}
ksort($a);
print_r($a);
And it works but i feel like there should be a much easier way :-s
Upvotes: 0
Views: 1304