Ternary Operator in PHP – Explained

If you don’t know what’s a ternary operator in PHP is, then you’re missing a cool feature of PHP. There are few operators in PHP which seems a bit complicated. Ternary Operator is one of them.

The reason it’s called ternary operator is exactly what you are thinking, it’s composed of three operands. (Operands are the things that are manipulated and operators are the symbols that represent specific actions.)

These three operands are –

  • A condition
  • A result for ‘true’
  • A result for ‘false’

This sounds a lot like ‘if statements’, right? Ternary Operator is a shorthand way of doing if statements.

How to use Ternary Operator in PHP

Still confused? Let’s check out an example.

First, there is a condition ($rating > 7), then there is a question mark. Then a ‘true’ result and a ‘false’ result after the colon. What this means is –

If $rating is greater than 7 then set $movie value to ‘Great!’, otherwise set it to ‘Average’. 

If we used if statement instead of using the ternary operator then our code would look like this –

So, if we used ‘if statements’, we would have to write five lines of code while using ternary operator we just wrote one line. Output is same in both cases.

Ternary Operator Shorthand

You can use this trick to make your logic even shorter. This only works with PHP 5.3+

Let’s check out how you can do that. For example,

Generally, you would write like this for above purpose. This is not many lines of code but still it’s three lines. Wouldn’t it be better if you could reduce that while getting the same output?

Now, here’s how you write those three lines of code in one line using ternary operator shorthand –

Better, right?

I hope you find this helpful. Don’t forget to share this with others if you found this helpful.

Leave a Reply

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