coopertrooper
coopertrooper

Reputation: 155

Setting a PHP array's value to 0 if its key does not exist as a value in another array

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.

Upvotes: 3

Views: 4450

Answers (4)

outis
outis

Reputation: 77420

foreach is more readable, but you can also use the array functions:

array_merge($second_array, 
            array_fill_keys(array_diff(array_keys($second_array), 
                                       $first_array), 
                            0));                        
# or
array_merge(
    array_fill_keys(array_keys($second_array), 0),
    array_intersect_key($second_array, array_flip($first_array)));
# or
function zero() {return 0;}

array_merge(
    array_map('zero', $second_array),
    array_intersect_key($second_array, array_flip($first_array)));

Upvotes: 0

erisco
erisco

Reputation: 14329

// get all keys of the second array that is not the value of the first array
$non_matches = array_diff(array_keys($second_array), $first_array);

// foreach of those keys, set their associated values to zero in the second array
foreach ($non_$matches as $match) {
    $second_array[$match] = 0;
}

Upvotes: 1

Borealid
Borealid

Reputation: 98509

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).

Upvotes: 2

benjy
benjy

Reputation: 4716

foreach($second_array as $name => $age) {
    if(in_array($name, $first_array) {
        //whatever
    }
    else {
        //set the value to zero
    }
}

Upvotes: 2

Related Questions