【问题标题】:Compare all array values with a single string - PHP将所有数组值与单个字符串进行比较 - PHP
【发布时间】:2015-08-25 17:19:51
【问题描述】:

有写这个的捷径吗?如下:

<?php

$true=1;
$false=0;

$valid = array (
                "part1" => $true,
                "part2" => $true,
                "part3" => $true
);

if($valid == $true){
echo "All the values are True!";
}else{
echo "At list one of the values is False";
}

?>

而不是这个:

 <?php

    if($valid['part1'] == $true && $valid['part2'] == $true && $valid['part3'] == $true{
    echo "All the values are True!";
    }else{
    echo "At list one of the values is False";
    }

    ?>

我已经尝试按照第一个示例中所示编写它,但它不起作用

【问题讨论】:

  • if (count(array_filter($valid)) == count($valid)) { echo 'All the values are Truthy'; } else { echo 'at least one of the values is falsey'; }
  • array_filter 可能比下面的array_unique 答案慢。
  • @mark use array_unique 并等于 1 将使代码更快,并且通常使用更少的代码
  • @QuakeCore 给出了最好的答案,但必须承认我没有看到这种方法

标签: php arrays string compare


【解决方案1】:
if(!in_array($false,$valid){
echo "All the values are True!";
}else{
echo "At list one of the values is False";
}

【讨论】:

  • 这是迄今为止最好的答案
  • 同意,只有两种可能性时的最佳方法。 +1
  • 很好的答案!谢谢!
【解决方案2】:

您可以使用array_keys' 第二个选项来搜索与您的变量匹配的值,并将结果数与数组中的元素总数进行比较:

if (count(array_keys($valid, $true)) == count($valid)) {
    echo "All the values are True!";
} else {
    echo "At leastone of the values is False";
}

【讨论】:

    【解决方案3】:

    它是一个数组而不是一个变量,你不能只是 === 它

    你必须使用

    if (count(array_unique($allvalues)) === 1 && end($allvalues) === 'true') {
    echo "All the values are True!";
    }else{
    echo "At list one of tha values is false";
    }
    

    【讨论】:

      【解决方案4】:

      你可以这样做:

      $array = array(
          'key1' => true,
          'key2' => true,
          'key3' => true,
      );
      
      $status = true;
      foreach($array as $key => $value) {
          if(!$value) {
              $status = false;
              break;
          }
      }
      if($status) {
          echo "All the values are True!";
      }
      else {
          echo "At list one of the values is False";
      }
      

      【讨论】:

      • 不是最好的方法,因为您正在错过更有效地执行此操作的机会。但这仍然是另一种方法
      • @BuddhiAbeyratne - 是的。在我的帖子之后,我看到了其他带有 in_array() 和 array_keys() 的遮阳篷,但我喜欢我的方式。总是很高兴知道如何在没有特殊功能的情况下做到这一点。
      猜你喜欢
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 2021-06-28
      • 2016-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多