PHP Tip #3: The Ternary Operator
This is probably one of my favorite PHP features. It can be a little complicated to get used to at first, but it really saves a lot of time & can be extremely useful.
The Ternary operator is another way of writing if…else. Here is the normal way of writing it:
1 2 3 4 5 |
if( $a ) { echo $b; } else { echo $c; } |
With the Ternary operator you would write this:
1 |
echo $a ? $b : $c; |
You can also chain Ternary’s together, but be warned it can get extremely complicated & most sites I have visited warn against using them for that reason. In my opinion, give it a go & see what you think. If you can use them then it’s another way for you to code. 🙂 Here’s what a chained Ternary statement looks like.
1 |
expression ? ( expression1 ? expression1a : expression1b ) : expression2 |
I’d give an example of a nested Ternary, but for the life of me I can’t think of a one. 😆
2 Comments
Emad
Thanks, finally got my head around the tenary operators…
Veneficus Unus
No problem. They take a little while to get round, but they are worth it. 🙂