【问题标题】:php more than one condition is truephp 多个条件为真
【发布时间】:2016-11-30 10:48:01
【问题描述】:

有多个变量说$a,$b,$c,$d 具有布尔值。 所以我想做的是。

if($a){echo 1;}
if($b){echo 2;}
if($c){echo 3;}
if($d){echo 4;}
and so on.. 50 variables

有没有更好的方法来做到这一点?
注意:可以有多个变量为真。

【问题讨论】:

  • 按顺序遍历变量,如果为真,则回显当前的迭代次数。这正是循环的用途。
  • 如果可能的话可以使用数组,然后用foreach循环或其他循环添加条件

标签: php if-statement


【解决方案1】:

您可以使用此代码进行迭代:

$a= $b = $c = TRUE;
$array = array(0=> $a,1=>$b,2=> $c);
foreach($array as $key => $value){
  if($value){
      echo $key;
    }
}

【讨论】:

    【解决方案2】:

    也许将所有布尔变量放在一个布尔数组中,并迭代数组以检查值

    $boolArray = array();
    $boolArray[0] = array($a, 1);
    $boolArray[1] = array($b, 2);
    $boolArray[2] = array($c, 3);
    
    
    ...
    
    for($x = 0; $x < count($boolArray); $x++) {
      if ($boolArray[x][1]) {  
         echo (string)$boolArray[x][2];
      }
    }
    

    【讨论】:

      【解决方案3】:

      我想你正在寻找这样的东西。

      <?php
      # Define the settings you already have
      $a = true;
      $b = true;
      $c = true;
      
      # Create an array with letters from a to z
      # Instead of this, you can create an array of field names like array('a', 'b', 'c', 'd');
      $options    = range('a', 'z');
      
      # Loop in the letters from above
      foreach($options as $id => $letter) {
      
          # Check if variable exists and boolean is true
          if(isset(${$letter}) && ${$letter} === true) {
      
              # Output number from id
              echo $id + 1;
          }
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-05
        • 2015-08-19
        • 2011-08-21
        • 2017-06-08
        • 2021-11-21
        • 1970-01-01
        • 2013-05-04
        • 2019-06-26
        相关资源
        最近更新 更多