How does shorthand if/else work? [PHP]

233 Views Asked by At

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.

2

There are 2 best solutions below

4
Sash On BEST ANSWER

The correct syntax is

condition ? then statement : else statement;

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

2
TMH On

The way to define it is

statement ? true : false;

So for your example, you also need a false value.

echo ($active_page === 'front-page') ? 'front-page' : 'Some default value.';

Here's a link I found that has some good information on them.

One point from that link, incase it breaks, is you can nest the inline ifs.

echo ($active_page === 'front-page') ? (($somevar > 5) ? 'Above 5' : 'Below 5') : 'Some default value.';