PHP Tip #3: The Ternary Operator

/ PHP / by Paul Robinson / 2 Comments
This post was published back on March 14, 2009 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

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:

With the Ternary operator you would write this:

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.

I’d give an example of a nested Ternary, but for the life of me I can’t think of a one. 😆

2 Comments

Author’s gravatar

Thanks, finally got my head around the tenary operators…

Reply
Older Comments
Newer Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more