PHP Ternary Operator the One Line If Else

I don’t know if it is just me or not; I have always liked optimizing my code. The awesome feeling when you learn that new trick and you cut your code from ten to three lines. It’s like leveling up in a game (insert Link getting loot sound here).

One of the biggest moments I can remember is when I discovered the Ternary Operator. What is that you ask?: It is basically an if/else statement on one line. Let’s look at an example of typical code.

if($level >= 10) {
    $sword = 'LEGENDARY';
} else {
    $sword = 'Pointy Stick';

So here we have five lines of code. It seems pretty straightforward, but can we optimize it more?: Yes, we can!

if($level >= 10) {$sword = 'LEGENDARY';} else {$sword = 'Pointy Stick';}

Now, if you came up with this; You’re smart, but not ninja smart (don’t buy that .guru yet.) There is a better way yet. Excited?: Well, you should be!

$sword = $level >= 10 ? 'LEGENDARY' : 'Pointy Stick';

So there are two expressions on your face right now. You are rolling your eyes and thinking, “Lame I already knew that” or you’re drooling on your desk right now.

So what is happening there?: Well, after the equals we are doing our comparison (This can have multiple tests also.) If the test would return true we do what is after the question mark(?) and if false we do what is after the colon(:). Now there are a lot of ways you could use this. Setting a variable is one way, but you can also use it in standard content.

echo 'The wizard dug into his pocket and found he had ',($gold > 0) ? $gold : 0),'gold!';

You can even nest them (try not to go overboard here!)

$name = isset($name) ? $name : (isset($nickname) ? $nickname : 'guest');

It is normally best not to go over one, as you can see it gets confusing fast. Just remember that someone might be reading your code later.

Leave your comments, questions, or advice below. I’m always up to learn how I can do something better or help someone out with what I know.

Leave a Reply

Your email address will not be published. Required fields are marked *