0

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?

1
  • 3
    Dog, cat AND monkey are ALL in array $B, so of course the if loop gets never called. What did you expect? Commented Mar 22, 2018 at 6:55

6 Answers 6

2

With use of php in_array() and ternary operator.

$A=['dog', 'cat', 'monkey'];
$B=['cat', 'rat', 'dog', 'monkey'];
foreach($A as $animal) {
    $result[] = in_array($animal, $B) ? "$animal exist": "$animal does not exist";
}
var_dump($result);
Sign up to request clarification or add additional context in comments.

Comments

1
<?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

Comments

0

you need to check exist or not like this

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

  foreach($A as $animal) {
    if(in_array($animal, $B)) {
      echo "exist";
    }
    else{
        echo 'not exist';
    }
  }
?>

Comments

0

Try the below to check which exist and which doesn't.

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

  foreach($A as $animal) {
    if(in_array($animal, $B)) {
      echo "$animal exists in \$B<br/>";
    }
    else{
        echo "$animal does not exist in \$B<br/>";
    }
  }
?>

Comments

0

Your condition is true every time because all elements of array A exists in array B. Try adding a new element and then see.

<?php
    $A=['dog', 'cat', 'monkey', 'kite'];
    $B=['cat', 'rat', 'dog', 'monkey'];

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

Think the logic first before implementing a program.

Comments

-1
<?php    /*try this function,,
array_key_exists(array_key, array_name)*/

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

foreach($A as $animal) {
if(array_key_exists($animal, $B)) {
  echo "$animal doesn't exist<br>";
  } else{echo"$animal doesnot exit<br>";}    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.