我正在使用以下示例代码:
<?php
$id = "a";
echo $id == "a" ? "Apple" : $id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others";
我想获得苹果的输出。但我得到了狗。任何人都可以帮助我。
来自关于三元运算符的说明: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
改用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
}
<?php
$id = "a";
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : ($id == "c" ? "Cat" : ($id == "d" ? "Dog" : "Others")));
尝试喜欢
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
如果条件为 false,则只有我放入()
中的剩余块才会执行。
尝试将你的条件分开
echo ($id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others"));
否则使用switch()
会更好
这里是 :
<?php
$id = "a";
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
?>
将 else 条件部分放在括号中:
echo $id == "a" ? "Apple" : ($id == "b" ? "Bat" : $id == "c" ? "Cat" : $id == "d" ? "Dog" : "Others");
引用运算符优先级