Based on the examples from this page, I have the working and non-working code samples below.
Working code using if
statement:
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 $test
outputs the expected result. The following works like a charm!
echo (empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />';
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:
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:
will return
From the PHP Manual
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>
Here are some interesting examples, with one or more varied conditions.
The
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: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, isecho
the result of the conditional operator:and this will display "Street is empty!" if it is empty, otherwise it will display the street2 address.