0

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

1 Answer 1

2

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

$a = array_replace($a, $b);

Set a key in a equal to 0 if it is not in b

foreach(array_diff_key($a, $b) as $k=>$v) {
   $a[$k] = 0;
}

demo

Sign up to request clarification or add additional context in comments.

4 Comments

Why doesn't it work with indexes starting from 0? array_merge() would concatenate the arrays, but array_replace() does what you want.
@Barmar, my keys are actually shoe sizes :D that's why i don't start at 0 :D
I learned a new PHP function here. I've known about array_merge, but not array_replace.
@Barmar I use it in many cases. More than array_merge, I think

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.