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!
Continue reading “PHP Ternary Operator the One Line If Else”