159

Based on the examples from this page, I wanted to convert the below if statement to a ternary operator.

Working code using if statement:

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

I am not sure how this should be written using a ternary operator so that the echo works only if street2 exists in the array and is not an empty string.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Steven
  • 19,224
  • 47
  • 152
  • 257
  • 2
    Your question is fooling some volunteers and researchers because you are not writing an assignment using a shorthand ternary expression (there is no "Elvis Operator") -- you are writing a longhand ternary expression. The difference is that you are declaring both of the returned values depending on the evaluation. In a shorthand evaluation, if the input value is "truthy", it is returned; if it is "falsey" then the fallback value is returned (this is the value declared after the Elvis Operator). There is also a noticeably poor implementation of the Null Coalescing Operator here too. – mickmackusa Apr 14 '20 at 02:39

16 Answers16

299

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 (condition) {
    /* condition is true, do something like echo */
}
else {
    /* condition is false, do something else */
}

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

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.

John Rasch
  • 62,489
  • 19
  • 106
  • 139
56

PHP 7+

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

echo $address['street2'] ?? 'Empty';
Dharman
  • 30,962
  • 25
  • 85
  • 135
Rabin Lama Dong
  • 2,422
  • 1
  • 27
  • 33
  • 8
    Just FYI, if `$address['street2']` is an empty string. It will accept it and won't return `'Empty'`. `isset() != empty()`. This will only work if the value is `null` – AFwcxx Jul 31 '18 at 06:41
  • Well, I was just providing an example. But I have modified the code. Thanks ! – Rabin Lama Dong Jul 31 '18 at 07:01
  • 2
    What is the output if `$address['street2']` is not empty? – AliN11 Oct 17 '19 at 12:36
  • If $address['street2'] is not empty, it will output some form of “true”. The usual form of the above is more like: `echo $address['street2'] ?? 'Empty';` however as mentioned, it is the “**null** coalescing operator” so it only tests for null and not empty. This is because ?? Is effectively a shorthand for isset(). – Brian C Oct 20 '19 at 07:14
  • 10
    Signed in just to downvote this answer. This doesn't do at all what's advertised. – TKoL Nov 26 '19 at 16:05
  • 12
    **THIS ANSWER IS WRONG!** Proof: https://ideone.com/bLJM55 It echoes out the result of `!empty($address['street2'])` which is true, and PHP's `echo` will print this as `1`. Yeah, bizarre, but that's how it is. – Sliq Aug 05 '21 at 17:30
  • 2
    `empty()` **NEVER** returns `null`, so `??` will never give the desired result. I absolutely **HATE** when incorrect answers poison the Stack Overflow knowledge pool and give provably incorrect advice to researchers! – mickmackusa Aug 11 '21 at 22:52
  • I rolled back the edit since it made the answer absolutely wrong. It still isn't completely true, but at least it shows a working example now. `!empty` would never return `null` so null-coalescing operator can't be used together with it. – Dharman Aug 11 '21 at 23:53
  • 2
    Dear researchers, this answer is still incorrect for the posted question. The null coalescing operator will catch a `null` value but not an empty string. Researchers should not use this answer and they should certainly not upvote it. It is bad advice. – mickmackusa Aug 12 '21 at 00:06
33

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

Arun Yokesh
  • 1,346
  • 17
  • 19
  • 4
    you got it from the short hand website and didn't even reference it – Richard Apr 10 '19 at 12:33
  • 1
    @Richard added references – Arun Yokesh Dec 23 '19 at 10:00
  • Is it ? In the context of StackOverflow it's always a thin line, I mean the Q asked for something, unable to find it by him/herself, and then somebody else delivered this content. Is it unfair to copy existing content if it helps and adds value to this Q/A ? I think answers on StackOverflow are not "your own content" ... hmmm – Sliq Feb 02 '20 at 17:44
  • 2
    First example is incorrect. The `)` is misplaced. It should precede the `?`. The complete statement should be `$is_admin = ($user['permissions'] == 'admin') ? true : false;` – user1934286 Jul 31 '20 at 22:00
  • Also, completely useless without an eplanation of what the examples do. – Daniel Bengtsson Jan 17 '22 at 22:46
28

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.

Keyboard ninja
  • 725
  • 6
  • 13
15

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.

The following example will work:

echo empty($address['street2']) ? 'empty' : 'not empty';
adrianbanks
  • 81,306
  • 22
  • 176
  • 206
13

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';
Learning and sharing
  • 1,378
  • 3
  • 25
  • 45
5

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

It looks like PHP doesn't work the same way as at least Javascript or 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.

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.

user276648
  • 6,018
  • 6
  • 60
  • 86
2

Conditional Welcome Message

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

Nested PHP Shorthand

echo 'Your score is:  '.($score > 10 ? ($age > 10 ? 'Average' : 'Exceptional') : ($age > 10 ? 'Horrible' : 'Average') );
Adnan
  • 571
  • 5
  • 15
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>

ᴄʀᴏᴢᴇᴛ
  • 2,939
  • 26
  • 44
Pathros
  • 10,042
  • 20
  • 90
  • 156
2

if else php shorthand ?

Try this

  ($value == 1) ? "selected" : "";
SIAMWEBSITE
  • 171
  • 1
  • 4
0

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 />');
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

horas_ro
  • 77
  • 2
  • 5
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");
rela589n
  • 817
  • 1
  • 9
  • 19
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.

Exception
  • 789
  • 4
  • 18
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';

-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;
Hoppeduppeanut
  • 1,109
  • 6
  • 20
  • 29
Sreejith N
  • 25
  • 5