如何用 elseif 部分编写 PHP 三元运算符?
我看到了 PHP 三元运算符的 if
和 else
部分的基本示例,如下所示:
echo (true) ? "yes" : "no"; //prints yes
echo (false) ? "yes" : "no"; //prints no
如何将这样的“elseif”部分放入三元运算符?
<?php
if($result->vocation == 1){
echo "Sorcerer";
}else if($result->vocation == 2){
echo 'Druid';
}else if($result->vocation == 3){
echo 'Paladin';
}else if($result->vocation == 4){
echo 'Knight';
}else if($result->vocation == 5){
echo 'Master Sorcerer';
}else if($result->vocation == 6){
echo 'Elder Druid';
}else if($result->vocation == 7){
echo 'Royal Paladin';
}else{
echo 'Elite Knight';
}
?>
最佳答案
三元组不是您想要的一个好的解决方案。它在您的代码中不可读,并且有更好的解决方案可用。
为什么不使用数组查找“map”或“dictionary”,像这样:
$vocations = array(
1 => "Sorcerer",
2 => "Druid",
3 => "Paladin",
...
);
echo $vocations[$result->vocation];
这个应用程序的三元组最终看起来像这样:
echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));
为什么会这样?因为 - 作为一个长行,如果这里出现问题,您将无法获得有效的调试信息,长度让人难以阅读,而且多个三元组的嵌套感觉很奇怪。
标准三元组简单易读,如下所示:
$value = ($condition) ? 'Truthy Value' : 'Falsey Value';
或
echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';
三元组实际上只是编写简单的 if else
语句的一种方便/更短的方法。上面的示例三元相同:
if ($some_condition) {
echo 'The condition is true!';
} else {
echo 'The condition is false!';
}
但是,复杂逻辑的三元组很快就会变得不可读,不再值得简洁。
echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));
即使有一些细心的格式将其分散到多行,也不是很清楚:
echo($result->group_id == 1
? "Player"
: ($result->group_id == 2
? "Gamemaster"
: ($result->group_id == 3
? "God"
: "unknown")));
关于php - 如何编写 PHP 三元运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17981723/