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:

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. :lol:

written by

WordPress wizard, coding ninja and all round cool guy. Loves Sci-Fi, geeky stuff, and of course Firefly. Currently a self confessed addict of Korean & Japanese Pop.



Author’s gravatar

Thanks, finally got my head around the tenary operators…


Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">