phpshorthandshorthand-if

How does shorthand if/else work? [PHP]


I've been trying to translate my PHP to the shorthand version, just for the fun of learning something new, but I can't get mine to work. I've looked at the many other questions about this on SO, but I couldn't adapt any of them to my situation.

What I want to translate to shorthand:

if ($active_page === "front-page") {echo $active_page;}

What I have:

echo ($active_page === 'front-page') ? 'front-page'; < Doesn't work

I know it's a very short sentence already, but just for the sake of learning something new I want to make it shorthand. When giving me the solution, please try to explain what I was doing wrong and how to approach it correctly in the future.


Solution

  • The correct syntax is

    condition ? then statement : else statement;
    

    Note, the else statement must be present. As the comments suggest, the else could be ''