【问题标题】:Long logical operator comparisons长逻辑运算符比较
【发布时间】:2013-03-30 05:38:01
【问题描述】:

我有三个决定结果的变量。只有两个结果,但结果是基于变量的。我想了一些很长的 if 语句,但我想知道是否有更简洁的方法。

$loggedin = (0 or 1) // If it is 0 then one outcome if 1 then it falls onto the next three variables
$status = (0-5) // 4 dead ends
$access = (0-3) // 
$permission = (0-9)

最后两个变量的不同组合会导致不同的结果,尽管有些组合是不相关的,因为它们是死胡同。

if ($loggedin == 1 && ($status == 1 || $status == 2 ) &&  'whattodohere' ):

我可以手动输入所有组合($access == 0 && ($var == 2 || $var = 6)),但我想知道是否有更好的方法来做到这一点,我不知道。

【问题讨论】:

    标签: php if-statement logical-operators comparison-operators


    【解决方案1】:

    看看 bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) - http://php.net/manual/en/function.in-array.php

    还可以查看 range(...) - http://php.net/manual/en/function.range.php

    $状态 == 1 || $status == 2 [... $status == n] 可以简化为 in_array( $status, range(0, $n) )

    使用 in_array & range 在性能方面成本更高,所以如果您确定只需要尝试 2 个不同的值,请改用 == 运算符。

    【讨论】:

      【解决方案2】:

      一种方法可能是使用 switch():http://php.net/manual/en/control-structures.switch.php

      例子:

      <?php
      /*
      $loggedin = (0 or 1) // If it is 0 then one outcome if 1 then it falls onto the next three variables
      $status = (0-5) // 4 dead ends
      $access = (0-3) // 
      $permission = (0-9) */
      
      $access = 1;
      $loggedin = 1;
      $status = 1;
      
      if ($loggedin == 1) {
       if ($status == 1 || $status == 2 ) {
              switch($access) {
                  case 0:
                  //do some coding
                  break;
      
                  case 1:
                  echo 'ACCESSS 1';
                  //do some coding
                  break;
      
                  default:
                  //Do some coding here when $access is issued in the cases above
                  break;
              }
          }
      }
      else {
          //Do coding when $loggedIn = 0
      } 
      
      ?>
      

      在示例中,ACCESS 1 将是输出。

      也许您还可以做一些数学运算并比较结果(在某些情况下取决于您想要达到的目标)。例如:

      <?php
      $permission = 1;
      $access = 2;
      $result = $permission * $access;
      if ($result > 0) {
          switch($result) {
              case 0:
              //do something
              break;
              case 1:
              //do something
              break;
              default:
              //Do something when value of $result not issued in the cases above
          }
      }
      ?>
      

      【讨论】:

        猜你喜欢
        • 2012-07-16
        • 1970-01-01
        • 1970-01-01
        • 2015-07-03
        • 2018-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多