如何检查值是否为';在php中数组中不存在吗?

如何检查值是否为';在php中数组中不存在吗?,php,arrays,if-statement,Php,Arrays,If Statement,我有以下php代码: <?php $A=['dog', 'cat', 'monkey']; $B=['cat', 'rat', 'dog', 'monkey']; foreach($A as $animal) { if(!in_array($animal, $B)) { echo "$animal doesn't exist<br>"; } } ?> 您需要检查是否存在 <?php $A=['dog', 'cat'

我有以下php代码:

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

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

您需要检查是否存在

<?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';
    }
  }
?>

您需要检查存在与否

<?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';
    }
  }
?>

尝试下面的方法检查哪些存在,哪些不存在

<?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/>";
    }
  }
?>

尝试下面的方法检查哪些存在,哪些不存在

<?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/>";
    }
  }
?>

在数组()中使用php
三元运算符

$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);

在数组()中使用php
三元运算符

$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);

您的条件每次都为true,因为数组
A
的所有元素都存在于数组
B
中。尝试添加新元素,然后查看

<?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>";
    }
?>

由于数组
A
的所有元素都存在于数组
B
中,因此每次您的条件都为true。尝试添加新元素,然后查看

<?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>";
    }
?>

狗、猫和猴子都在数组中
$B
,所以当然if循环从未被调用过。你期待什么?狗、猫和猴子都在数组中
$B
,所以当然if循环从未被调用过。你期待什么?