148

根据this page的示例,我想将以下if语句转换为三元运算符。

if使用语句的工作代码:

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

我不确定应该如何使用三元运算符来编写它,以便echo只有street2在数组中存在并且不是空字符串时才有效。

4

16 回答 16

279

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

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

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

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

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

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

于 2009-10-01T21:30:55.037 回答
50

PHP 7+

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

echo $address['street2'] ?? 'Empty';
于 2017-07-06T10:42:49.277 回答
31

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

于 2014-12-08T10:09:17.117 回答
17

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

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

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

于 2018-10-16T14:32:22.687 回答
14

三元运算符只是 if/else 块的简写。你的工作代码没有 else 条件,所以不适合这个。

以下示例将起作用:

echo empty($address['street2']) ? 'empty' : 'not empty';
于 2009-10-01T21:28:59.453 回答
8

Quick and short way:

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

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

$color = "blue";

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

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

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

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

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

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

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

Update in PHP 7+

// Check if the value exists
echo $_GET['user'] ?? "Undefined"; 
// Before isset($_GET['user']) ? $_GET['user'] : 'undefined';

// Multiple conditions can be added
echo $_GET['user'] ?? $_POST['user'] ?? $color ?? 'Undefined';
于 2018-07-03T21:04:55.987 回答
5

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

看起来 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');

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

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

  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

From the documentation: 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.

于 2014-09-24T10:40:28.887 回答
2

有条件的欢迎信息

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

嵌套 PHP 速记

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );
于 2014-05-15T12:35:33.460 回答
2

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

<?=(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>

于 2015-08-02T18:48:58.137 回答
1

if else php shorthand ?

Try this

  ($value == 1) ? "selected" : "";
于 2021-05-28T10:28:00.627 回答
0

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

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

我认为它应该工作,你也可以使用:

echo (empty($address['street2']) ? 'Yes <br />' : 'No <br />');
于 2013-12-07T04:24:31.700 回答
0

There's also a shorthand ternary operator and it looks like this:

(expression1) ?: expression2 will return expression1 if it evaluates to true or expression2 otherwise.

Example:

$a = 'Apples';
echo ($a ?: 'Oranges') . ' are great!';

will return

Apples are great!

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

From the PHP Manual

于 2018-01-09T12:55:50.213 回答
0

I think you probably should not use ternary operator in php. Consider next example:

<?php

function f1($n) {
    var_dump("first funct");
    return $n == 1;
}

function f2($n) {
    var_dump("second funct");
    return $n == 2;
}


$foo = 1;
$a = (f1($foo)) ? "uno" : (f2($foo)) ? "dos" : "tres";
print($a);

How do you think, what $a variable will contain? (hint: dos) And it will remain the same even if $foo variable will be assigned to 2.

To make things better you should either refuse to using this operator or surround right part with braces in the following way:

$a = (f1($foo)) ? "uno" : ((f2($foo)) ? "dos" : "tres");
于 2019-10-30T17:08:36.060 回答
0

Ternary Operator is basically shorthand for if/else statement. We can use to reduce few lines of code and increases readability.

Your code looks cleaner to me. But we can add more cleaner way as follows-

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

Another way-

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

Note- I have added bracket to whole expression to make it cleaner. I used to do this usually to increase readability. With PHP7 we can use Null Coalescing Operator / php 7 ?? operator for better approach. But your requirement it does not fit.

于 2020-06-13T13:48:06.387 回答
0


I dont think i found the answer in all the above solutions. Some are also wrong.

To tests if a variable (or an element of an array, or a property of an object) exists (and is not null) use: echo isset($address['street2']) ? $address['street2'] : 'Empty';

To tests if a variable (...) contains some non-empty data use:
echo !empty($address['street2']) ? $address['street2'] : 'Empty';

于 2021-02-08T06:55:46.867 回答
-1

If first variable($a) is null, then assign value of second variable($b) to first variable($a)

 $a = 5;
 $b = 10;   

 $a != ''?$a: $a = $b;

 echo $a;
于 2020-09-14T04:42:12.007 回答