Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check associative array key exists in another array

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading