【问题标题】:PHP shortcode condition not work [duplicate]PHP短代码条件不起作用[重复]
【发布时间】:2014-05-15 01:41:54
【问题描述】:

我正在使用下面的示例代码:

<?php
$id = "a";
echo $id == "a" ? "Apple" : $id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others";

我想以 Apple 的形式输出。但我得到了。任何人都可以请帮助我。

【问题讨论】:

标签: php shortcode


【解决方案1】:

来自三元运算符的注释:http://www.php.net/manual/en/language.operators.comparison.php

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>

【讨论】:

    【解决方案2】:

    方式#1

    改用switch,它还有助于您的代码更具可读性..

    switch($id)
    {
        case "a":
            echo "Apple";
            break;
        
        case "b":
            echo "Bat";
            break;
        
        //Your code...
        
        //More code..
    }
    

    方式#2

    你也可以使用array_key_exists()

    $id = "a";
    $arr = ["a"=>"Apple","b"=>"Bat"];
    if(array_key_exists($id,$arr))
    {
        echo $arr[$id]; //"prints" Apple
    }
    

    【讨论】:

      【解决方案3】:
      <?php
      
      $id = "a";
      
      echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : ($id == "c" ? "Cat" : ($id == "d" ? "Dog" : "Others")));
      

      【讨论】:

        【解决方案4】:

        试试看

        echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
        

        如果条件为假,那么只有我放在() 中的剩余块将执行。

        【讨论】:

          【解决方案5】:

          试着把你的条件分开

          echo ($id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others"));
          

          否则使用switch()会更好

          【讨论】:

            【解决方案6】:

            这里是:

            <?php
            $id = "a";
            echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
            ?>
            

            【讨论】:

              【解决方案7】:

              将else条件部分放在括号中:

              echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
              

              参考operator precedence

              【讨论】:

                猜你喜欢
                • 2013-02-06
                • 1970-01-01
                • 1970-01-01
                • 2014-06-04
                • 1970-01-01
                • 2013-06-14
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多