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 />';
It's the elvis operator (google it :P) you are looking for.
It returns the value of the variable or default if the variable is empty.
Basic True / False Declaration
Conditional Welcome Message
Conditional Items Message
I think you used the brackets the wrong way. Try this:
I think it should work, you can also use:
Conditional Welcome Message
Nested PHP Shorthand
PHP 7+
As of PHP 7, this task can be performed simply by using the Null coalescing operator like this :
echo !empty($address['street2']) ?? 'Empty';
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#.
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):
$score > 10
? yes$age > 10
? no, so the current$age > 10 ? 'Average' : 'Exceptional'
returns 'Exceptional''Exceptional' ? 'Horrible' : 'Average'
which returns 'Horrible', as 'Exceptional' is truthyFrom the documentation: http://php.net/manual/en/language.operators.comparison.php