Hawk Solo
Hawk Solo

Reputation: 21

Matching arrays and update value in array one

I'm trying to to update the value of array one, if it is found within array two, e.g:

$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish']; 

I need to get the data back as:

$has_pets = ['Cat' => 1, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 1];

I've tried playing with the array_intersect() function and a foreach loop but for the life of me I could not get it working.

Cheers in advance

Upvotes: 2

Views: 333

Answers (4)

Osama
Osama

Reputation: 3030

Use foreach and in_array()

$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish']; 
foreach($all_pets as $key=>$value){
    if(in_array($key,$user_has){
        $indexes = array_keys($user_has,$key); 
        $all_pets[$key]= count($indexes);
    }
}

Upvotes: 0

Eddie
Eddie

Reputation: 26854

You can use foreach to loop thru the array $user_has. Use isset() to check if the key exist in $all_pets. If it does, change the value.

$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish']; 

foreach( $user_has as $value ) {
    if ( isset( $all_pets[ $value ] ) ) $all_pets[ $value ]++;
}

This will result to:

Array
(
    [Cat] => 1
    [Dog] => 0
    [Bird] => 0
    [Rabbit] => 0
    [Fish] => 1
)

Upvotes: 3

billyonecan
billyonecan

Reputation: 20270

You can use array_merge() and array_count_values():

array_merge($all_pets, array_count_values($user_has));

Here's a demo

array_count_values() counts the occurrences of each value in the array, and returns an array with value => count pairs.

array_merge() merges the arrays, if they have the same string keys, then the later value for that key will overwrite the previous one.

Upvotes: 3

Mina Ragaie
Mina Ragaie

Reputation: 475

<?php 

$all_pets = ['Cat' => 0, 'Dog' => 0, 'Bird' => 0, 'Rabbit' => 0, 'Fish' => 0];
$user_has = ['Cat', 'Fish']; 


$has_pets = array();

foreach ($user_has as $key => $pet) {
    $has_pets[$pet]++;
}

print_r(array_merge($all_pets, $has_pets));
?>

Upvotes: 0

Related Questions