Home > Mobile >  Check associative array key exists in another array
Check associative array key exists in another array

Time:01-25

I have two associative array, and I am trying to find the keys of the first array if they are present in second array.

<?php
    $team_member = ["Person_1" => 0, "Person_2" => 0, "Person_3" => 0, "Person_4" => 0];
    $today_active_member = ["Person_1" => 0, "Person_3" => 0, "Person_4" => 0];

    $i = count($team_member);

    while($i--){ //4, 3, 2, 1, false
        if(in_array(key($team_member), $today_active_member)) { // check is key available in second array?
            echo key($team_member) . " is present today.<br/>";
            next($team_member); // goes to the next key
            // code goes here
        } else {
            echo key($team_member) . " isn't present today.<br/>";
            next($team_member); // goes to the next key
        }
    }

But above code is not giving the correct output. now the output is:

Person_1 is present today.
Person_2 is present today.
Person_3 is present today.
Person_4 is present today.

It should output:

Person_1 is present today.
Person_2 isn't present today.
Person_3 is present today.
Person_4 is present today.

How can I find those keys of first array which are in second array. I've also tried to solve the problem with array_keys(), array_search() but it doesn't work

CodePudding user response:

Instead, you should use the array_key_exists() function, which takes two arguments: the key you want to check for and the array you want to check in.

<?php
$team_member = ["Person_1" => 0, "Person_2" => 0, "Person_3" => 0, "Person_4" => 0];
$today_active_member = ["Person_1" => 0, "Person_3" => 0, "Person_4" => 0];

$i = count($team_member);

while($i--){ 
    if(in_array(key($team_member), array_keys($today_active_member))) { 
        echo key($team_member) . " is present today.<br/>";
        next($team_member); 
    } else {
        echo key($team_member) . " isn't present today.<br/>";
        next($team_member); 
    }
}

PHP online : https://onlinephp.io/c/48b7c

CodePudding user response:

There is a far simpler way using a foreach loop and array_key_exists()

$team_member = ["Person_1" => 0, "Person_2" => 0, "Person_3" => 0, "Person_4" => 0];
$today_active_member = ["Person_1" => 0, "Person_3" => 0, "Person_4" => 0];

foreach( $team_member as $key=>$val){
    if (array_key_exists($key, $today_active_member)){
        echo $key . " is present today.<br/>";
    } else {
        echo $key . " isn't present today.<br/>";
    }
}

RESULT

Person_1 is present today.<br/>
Person_2 isn't present today.<br/>
Person_3 is present today.<br/>
Person_4 is present today.<br/>
  •  Tags:  
  • php
  • Related