How to replace "if" statement with a ternary operator ( ? : )?

Viewed 429507

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.

16 Answers

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.

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

if else php shorthand ?

Try this

  ($value == 1) ? "selected" : "";

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

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

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.


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

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;
Related