phparraysarray-difference

Find values in a flat array not found in another flat array


I have this php code:

$A = ['dog', 'cat', 'monkey'];
$B = ['cat', 'rat', 'dog', 'monkey'];

foreach ($A as $animal) {
    if (!in_array($animal, $B)) {
        echo "$animal doesn't exist<br>";
    }
}

But the if statement never executes. What I'm I doing wrong? What is the proper way to check if a value doesn't exist in array?


Solution

  • <?php
      $A=['dog', 'cat', 'monkey'];
      $B=['cat', 'rat', 'dog', 'monkey'];
    
      foreach($B as $animal) {
        if(!in_array($animal, $A)) {
          echo "$animal doesn't exist<br>";
        }
      }
    ?>
    

    Output: rat doesn't exist