如何在 PHP 中使用三元运算符 (?:) 作为“if / else”的简写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1506527/
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 02:51:58  来源:igfitidea点击:

How do I use the ternary operator ( ? : ) in PHP as a shorthand for "if / else"?

phpternary-operatorconditional-operator

提问by Steven

Based on the examples from this page, I have the working and non-working code samples below.

基于此页面中的示例,我有下面的工作和非工作代码示例。

Working code using ifstatement:

使用if语句的工作代码:

if (!empty($address['street2'])) echo $address['street2'].'<br />';

Non-working code using ternary operator:

使用三元运算符的非工作代码:

$test = (empty($address['street2'])) ? 'Yes <br />' : 'No <br />';

// Also tested this
(empty($address['street2'])) ? 'Yes <br />' : 'No <br />';

UPDATE
After Brian's tip, I found that echoing $testoutputs the expected result. The following works like a charm!

更新
在 Brian 的提示之后,我发现 echoing$test输出了预期的结果。下面的作品就像一个魅力!

echo (empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />';

回答by John Rasch

The

(condition) ? /* value to return if condition is true */ 
            : /* value to return if condition is false */ ;

syntax is not a "shorthand if" operator (the ?is called the conditional operator) because you cannot execute code in the same manner as if you did:

语法不是“速记 if”运算符(?称为条件运算符),因为您无法以与执行代码相同的方式执行代码:

if (condition) {
    /* condition is true, do something like echo */
}
else {
    /* condition is false, do something else */
}

In your example, you are executing the echostatement when the $addressis not empty. You can't do this the same way with the conditional operator. What you can do however, is echothe result of the conditional operator:

在您的示例中,echo$address不为空时,您正在执行该语句。您不能使用条件运算符以相同的方式执行此操作。但是,您可以做echo的是条件运算符的结果:

echo empty($address['street2']) ? "Street2 is empty!" : $address['street2'];

and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.

这将显示“街道是空的!” 如果为空,否则将显示 street2 地址。

回答by Rabin Lama Dong

PHP 7+

PHP 7+

As of PHP 7, this task can be performed simply by using the Null coalescing operatorlike this :

从 PHP 7 开始,可以简单地使用Null 合并运算符来执行此任务,如下所示:

echo !empty($address['street2']) ?? 'Empty';

echo !empty($address['street2']) ?? 'Empty';

回答by Arun Yokesh

Basic True / False Declaration

基本真/假声明

$is_admin = ($user['permissions'] == 'admin' ? true : false);

Conditional Welcome Message

有条件的欢迎信息

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Conditional Items Message

条件项目消息

echo 'Your cart contains '.$num_items.' item'.($num_items != 1 ? 's' : '').'.';

ref: https://davidwalsh.name/php-ternary-examples

参考:https: //davidwalsh.name/php-ternary-examples

回答by adrianbanks

The ternary operator is just a shorthand for and if/else block. Your working code does not have an else condition, so is not suitable for this.

三元运算符只是 and if/else 块的简写。您的工作代码没有 else 条件,因此不适合于此。

The following example will work:

以下示例将起作用:

echo empty($address['street2']) ? 'empty' : 'not empty';

回答by Keyboard ninja

It's the Ternary operator a.k.a Elvis operator (google it :P) you are looking for.

这是您正在寻找的三元运算符又名 Elvis 运算符(谷歌它:P)。

echo $address['street2'] ?: 'Empty'; 

It returns the value of the variable or default if the variable is empty.

如果变量为空,则返回变量的值或默认值。

回答by user276648

Note that when using nested conditional operators, you may want to use parenthesisto avoid possible issues!

请注意,在使用嵌套条件运算符时,您可能需要使用括号来避免可能出现的问题!

It looks like PHP doesn't work the same way as at least Javascript or C#.

看起来 PHP 的工作方式至少与 Javascript 或 C# 不同。

$score = 15;
$age = 5;

// The following will return "Exceptional"
echo 'Your score is: ' . ($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average'));

// The following will return "Horrible"
echo 'Your score is: ' . ($score > 10 ? $age > 10 ? 'Average' : 'Exceptional' : $age > 10 ? 'Horrible' : 'Average');

The same code in Javascript and C# return "Exceptional" in both cases.

Javascript 和 C# 中的相同代码在这两种情况下都返回“Exceptional”。

In the 2nd case, what PHP does is (or at least that's what I understand):

在第二种情况下,PHP 的作用是(或者至少我是这么理解的):

  1. is $score > 10? yes
  2. is $age > 10? no, so the current $age > 10 ? 'Average' : 'Exceptional'returns 'Exceptional'
  3. then, instead of just stopping the whole statement and returning 'Exceptional', it continues evaluating the next statement
  4. the next statement becomes 'Exceptional' ? 'Horrible' : 'Average'which returns 'Horrible', as 'Exceptional' is truthy
  1. $score > 10?是的
  2. $age > 10?不,所以当前$age > 10 ? 'Average' : 'Exceptional'返回“异常”
  3. 然后,它不仅停止整个语句并返回 'Exceptional',而是继续评估下一个语句
  4. 下一个语句变成'Exceptional' ? 'Horrible' : 'Average'返回“Horrible”,因为“Exceptional”是真的

From the documentation: http://php.net/manual/en/language.operators.comparison.php

从文档:http: //php.net/manual/en/language.operators.comparison.php

It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious.

建议您避免“堆叠”三元表达式。PHP 在一条语句中使用多个三元运算符时的行为并不明显。

回答by Learning and sharing

Quick and short way:

快捷方式:

echo $address['street2'] ? : "No";

Here are some interesting examples, with one or more varied conditions.

以下是一些有趣的示例,具有一种或多种不同的条件。

$color = "blue";

// Condition #1 Show color without specifying variable 
echo $color ? : "Undefined";
echo "<br>";

// Condition #2
echo $color ? $color : "Undefined";
echo "<br>";

// Condition #3
echo ($color) ? $color : "Undefined";
echo "<br>";

// Condition #4
echo ($color == "blue") ? $color : "Undefined";
echo "<br>";

// Condition #5
echo ($color == "" ? $color : ($color == "blue" ? $color : "Undefined"));
echo "<br>";

// Condition #6
echo ($color == "blue" ? $color : ($color == "" ? $color : ($color == "" ? $color : "Undefined")));
echo "<br>";

// Condition #7
echo ($color != "") ? ($color != "" ? ($color == "blue" ? $color : "Undefined") : "Undefined") : "Undefined";
echo "<br>";

回答by Adnan

Conditional Welcome Message

有条件的欢迎信息

echo 'Welcome '.($user['is_logged_in'] ? $user['first_name'] : 'Guest').'!';

Nested PHP Shorthand

嵌套的 PHP 速记

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );

回答by Pathros

You can do this even shorter by replacing echowith <?= code ?>

您可以通过替换echo为更短的时间<?= code ?>

<?=(empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />'?>

<?=(empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />'?>

This is useful especially when you want to determine, inside a navbar, whether the menu option should be displayed as already visited (clicked) or not:

这特别有用,尤其是当您想在导航栏中确定菜单选项是否应显示为已访问(单击)时:

<li<?=($basename=='index.php' ? ' class="active"' : '')?>><a href="index.php">Home</a></li>

<li<?=($basename=='index.php' ? ' class="active"' : '')?>><a href="index.php">Home</a></li>

回答by user2909855

I think you used the brackets the wrong way. Try this:

我认为您以错误的方式使用了括号。尝试这个:

$test = (empty($address['street2']) ? 'Yes <br />' : 'No <br />');

I think it should work, you can also use:

我认为它应该有效,您也可以使用:

echo (empty($address['street2']) ? 'Yes <br />' : 'No <br />');