Is there any kind of function or quick process for comparing two arrays in PHP in a way that if the value of one array exists as a key in the second array, the second array maintains its key's value, otherwise that key's value gets set to 0.

For example,

$first_array = array('fred', 'george', 'susie');

$second_array = array(
                'fred' => '21', 
                'george' => '13',     
                'mandy' => '31',     
                'susie' => '11'

After comparing the two, ideally my final array would be:

Fred > 21
George > 13
Mandy > 0 
Susie > 11

Where Mandy was set to 0 because the key didn't exist as a value in the first array…..

I know it's probably kind of an odd thing to want to do! But any help would be great.


could be done with array_walk() or array_map() or foreach() as below

Written by Dagon

interesting, thanks Dagon. I'll look those functions up.

Written by coopertrooper

Accepted Answer

foreach ($second_array as $key=>$val) {
    if (!in_array($key, $first_array))) {
        $second_array[$key] = 0;

Although you may want to build the first array as a set so that the overall runtime will be O(N) instead of O(N^2).

Written by Borealid
This page was build to provide you fast access to the question and the direct accepted answer.
The content is written by members of the community.
It is licensed under cc-wiki