I've tried using the examples from this page, but I can't output any results.

This is my IF statement that works:

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

And this is my none-working shorthand code

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

// Also tested this
(empty($address['street2'])) ? 'Yes <br />' : 'No <br />';

What am I doing wrong?

After Brians tip, I discovered what went wrong. Echoing $test outputs the result. So then I tried the following:

echo (empty($storeData['street2'])) ? 'Yes <br />' : 'No <br />';

And that worked like a charm!


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';
+2  A: 


(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