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.
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
echostatement when the$addressis not empty. You can’t do this the same way with the conditional operator. What you can do however, isechothe result of the conditional operator:and this will display “Street is empty!” if it is empty, otherwise it will display the street2 address.