问题描述
如何用elseif部分编写PHP三元运算符?
How do I write a PHP ternary operator with the elseif portion?
我看到了PHP三元运算符的if
和else
部分的基本示例,如下所示:
I see basic examples with the if
and else
portions of the PHP ternary operator like this:
echo (true) ? "yes" : "no"; //prints yes
echo (false) ? "yes" : "no"; //prints no
如何将这样的"elseif"部分放入三元运算符中?
How do I get the "elseif" portion like this into the ternary operator?
<?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';
}
?>
推荐答案
三元组并不是您想要的理想解决方案.它不会在您的代码中可读,并且有很多更好的解决方案.
A Ternary is not a good solution for what you want. It will not be readable in your code, and there are much better solutions available.
为什么不使用数组查找"map"或"dictionary",就像这样:
Why not use an array lookup "map" or "dictionary", like so:
$vocations = array(
1 => "Sorcerer",
2 => "Druid",
3 => "Paladin",
...
);
echo $vocations[$result->vocation];
此应用程序的三元最终看起来像这样:
A ternary for this application would end up looking like this:
echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));
为什么这样不好?因为-作为一条长长的线,如果这里出现问题,您将不会获得有效的调试信息,因此长度很难读取,加上多个三元组的嵌套感觉很奇怪.
Why is this bad? Because - as a single long line, you would get no valid debugging information if something were to go wrong here, the length makes it difficult to read, plus the nesting of the multiple ternaries just feels odd.
标准三元组简单易读,看起来像这样:
A Standard Ternary is simple, easy to read, and would look like this:
$value = ($condition) ? 'Truthy Value' : 'Falsey Value';
或
echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';
三元数实际上只是编写简单的if else
语句的便捷/简短方式.上面的三元示例与:
A ternary is really just a convenient / shorter way to write a simple if else
statement. The above sample ternary is the same as:
if ($some_condition) {
echo 'The condition is true!';
} else {
echo 'The condition is false!';
}
但是,用于复杂逻辑的三元很快就变得不可读,因此不再是简短的事了.
However, a ternary for a complex logic quickly becomes unreadable, and is no longer worth the brevity.
echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));
即使采用了一些细心的格式将其分布在多行中,也不是很清楚:
Even with some attentive formatting to spread it over multiple lines, it's not very clear:
echo($result->group_id == 1
? "Player"
: ($result->group_id == 2
? "Gamemaster"
: ($result->group_id == 3
? "God"
: "unknown")));
这篇关于如何编写PHP三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!