我使用下面的示例代码:
<?php
$id = "a";
echo $id == "a" ? "Apple" : $id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others";
我希望输出 Apple 。但我得到了狗。任何人都可以帮助我。
答案 0 :(得分:3)
关于三元运算符的注释: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.
?>
答案 1 :(得分:2)
使用switch
代替它也可以帮助您的代码更具可读性。
switch($id)
{
case "a":
echo "Apple";
break;
case "b":
echo "Bat";
break;
//Your code...
//More code..
}
您还可以使用array_key_exists()
$id = "a";
$arr = ["a"=>"Apple","b"=>"Bat"];
if(array_key_exists($id,$arr))
{
echo $arr[$id]; //"prints" Apple
}
答案 2 :(得分:0)
尝试
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
如果条件为false,那么只有我在()
中放置的剩余块才会执行。
答案 3 :(得分:0)
<?php
$id = "a";
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : ($id == "c" ? "Cat" : ($id == "d" ? "Dog" : "Others")));
答案 4 :(得分:0)
尝试将您的条件分开
echo ($id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others"));
否则使用switch()
会更好
答案 5 :(得分:0)
这是:
<?php
$id = "a";
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
?>
答案 6 :(得分:0)
将else条件部分放在括号中:
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");