如何编写 PHP 三元运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17981723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 16:45:34  来源:igfitidea点击:

How to write a PHP ternary operator

phpternary-operator

提问by dynamitem

How do I write a PHP ternary operator with the elseif portion?

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

I see basic examples with the ifand elseportions of the PHP ternary operator like this:

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

echo (true)  ? "yes" : "no";    //prints yes
echo (false) ? "yes" : "no";    //prints no

How do I get the "elseif" portion like this into the ternary operator?

如何将这样的“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';
  }
?>

回答by random_user_name

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.

三元不是您想要的好解决方案。它不会在您的代码中可读,并且有更好的解决方案可用。

Why not use an array lookup "map" or "dictionary", like so:

为什么不使用数组查找“map”或“dictionary”,如下所示:

$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 Ternaryis simple, easy to read, and would look like this:

标准三元很简单,易于阅读,如下所示:

$value = ($condition) ? 'Truthy Value' : 'Falsey Value';

or

或者

echo ($some_condition) ? 'The condition is true!' : 'The condition is false.';

A ternary is really just a convenient / shorter way to write a simple if elsestatement. The above sample ternary is the same as:

三元实际上只是编写简单if else语句的一种方便/更短的方法。上面的示例三元与:

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")));

回答by Orangepill

Since this would be a common task I would suggest wrapping a switch/case inside of a function call.

由于这将是一项常见任务,我建议将 switch/case 包装在函数调用中。

function getVocationName($vocation){
    switch($vocation){
        case 1: return "Sorcerer"; break;
        case 2: return 'Druid'; break;
        case 3: return 'Paladin'; break;
        case 4: return 'Knight'; break;
        case 5: return 'Master Sorcerer'; break;
        case 6: return 'Elder Druid'; break;
        case 7: return 'Royal Paladin'; break;
        default: return 'Elite Knight'; break;
    }
}

echo getVocationName($result->vocation);

回答by thelolcat

echo ($result ->vocation == 1) ? 'Sorcerer'
        : ($result->vocation == 2) ? 'Druid'
           :  ($result->vocation == 3) ? 'Paladin'
                    ....

;

It's kind of ugly. You should stick with normal ifstatements.

有点丑。你应该坚持使用正常的if陈述。

回答by Eric Leschinski

How to write a basic PHP Ternary Operator:

如何编写基本的 PHP 三元运算符:

($your_boolean) ? 'This is returned if true' : 'This is returned if false';

Example:

例子:

$myboolean = true;
echo ($myboolean) ? 'foobar' : "penguin";
foobar

echo (!$myboolean) ? 'foobar' : "penguin";
penguin

A PHP ternary operator with an 'elseif' crammed in there:

一个带有“elseif”的 PHP 三元运算符:

$chow = 3;
echo ($chow == 1) ? "one" : ($chow == 2) ? "two" : "three";
three

But please don't nest ternary operators except for parlor tricks. It's a bad code smell.

但请不要嵌套三元运算符,除了客厅技巧。这是一种糟糕的代码气味。

回答by madshvero

I'd rather than ternary if-statements go with a switch-case. For example:

我宁愿三元 if 语句与 switch-case 一起使用。例如:

switch($result->vocation){
case 1:
    echo "Sorcerer";
    break;
case 2:
    echo "Druid";
    break;
case 3:
    echo "Paladin";
    break;
case 4:
    echo "Knight";
    break;
case 5:
    echo "Master Sorcerer";
    break;
case 6:
    echo "Elder Druid";
    break;
case 7:
    echo "Royal Paladin";
    break;
default:
    echo "Elite Knight";
    break;
}

回答by exussum

You wouldn't: it's messy and hard to read.

你不会:它很乱,很难阅读。

You're looking for the switchstatement in the first case. The second is fine as it is but still could be converted for consistency

您正在寻找switch第一种情况下的声明。第二个很好,但仍然可以转换为一致性

Ternary statements are much more suited to boolean values and alternating logic.

三元语句更适合布尔值和交替逻辑。

回答by bizzehdee

To be honest, a ternary operator would only make this worse, what i would suggest if making it simpler is what you are aiming at is:

老实说,三元运算符只会使情况变得更糟,如果让它更简单,我建议您的目标是:

$groups = array(1=>"Player", 2=>"Gamemaster", 3=>"God");
echo($groups[$result->group_id]);

and then a similar one for your vocations

然后为你的职业做一个类似的

$vocations = array(
  1=>"Sorcerer",
  2=>"Druid",
  3=>"Paladin",
  4=>"Knight",
  ....
);
echo($vocations[$result->vocation]);

With a ternary operator, you would end up with

使用三元运算符,您最终会得到

echo($result->group_id == 1 ? "Player" : ($result->group_id == 2 ? "Gamemaster" : ($result->group_id == 3 ? "God" : "unknown")));

Which as you can tell, only gets more complicated the more you add to it

正如你所知道的,你添加的越多只会变得越复杂

回答by federico-t

In addition to all the other answers, you could use switch. But it does seem a bit long.

除了所有其他答案外,您还可以使用switch. 不过好像有点长。

switch ($result->vocation) {
case 1:
    echo 'Sorcerer';
    break;

case 2:
    echo 'Druid';
    break;

case 3:
    echo 'Paladin';
    break;

case 4:
    echo 'Knight';
    break;

case 5:
    echo 'Master Sorcerer';
    break;

case 6:
    echo 'Elder Druid';
    break;

case 7:
    echo 'Royal Paladin';
    break;

default:
    echo 'Elite Knight';
    break;
}

回答by Jann Anthony Briza

You could also do:

你也可以这样做:

echo "yes" ?: "no" // Assuming that yes is a variable that can be false.

Instead of:

代替:

echo (true)  ? "yes" : "no";

回答by DevWL

PHP 8 (Left-associative ternary operator change)

PHP 8(左关联三元运算符更改)

Left-associative ternary operator deprecation https://wiki.php.net/rfc/ternary_associativity. The ternary operator has some weird quirks in PHP. This RFC adds a deprecation warning for nested ternary statements. In PHP 8, this deprecation will be converted to a compile time error.

左关联三元运算符弃用https://wiki.php.net/rfc/ternary_associativity。三元运算符在 PHP 中有一些奇怪的怪癖。此 RFC 为嵌套的三元语句添加了弃用警告。在 PHP 8 中,这种弃用将转换为编译时错误。

1 ? 2 : 3 ? 4 : 5;   // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok

source: https://stitcher.io/blog/new-in-php-74#numeric-literal-separator-rfc

来源:https: //stitcher.io/blog/new-in-php-74#numeric-literal-separator-rfc