php - 如何编写 PHP 三元运算符

标签 php ternary-operator

如何用 elseif 部分编写 PHP 三元运算符?

我看到了 PHP 三元运算符的 ifelse 部分的基本示例,如下所示:

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/

相关文章:

javascript - 如果选择选项是 ""想要使用 javascript 三元组,则需要显示空

c# - C# 中哪个三元运算符最受欢迎且使用最多?

php - 用于电子邮件模板和前端图像和链接的 Joomla 目录文件夹

php - 拉拉维尔。如果数据库正在播种,则禁用观察者方法

c - 条件运算符的问题

c++ - 使用三元运算符初始化引用变量?

php - Mysqli 检索表打印标题而不是数据

PHP:PDO+mysql 无法使用管道符号 (|)

javascript - Ajax 内容加载数据库值不起作用

c# - 我可以使用三元运算符来设置泛型方法参数吗?