Home > Tutorials > PHP > PHP Tip #3: The Ternary Operator
Permalink to PHP Tip #3: The Ternary Operator

PHP Tip #3: The Ternary Operator

by on 03.14.2009 | 2 comments

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 [...]

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:

if( $a ) {
  echo $b;
} else {
  echo $c;
}

With the Ternary operator you would write this:

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.

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

TAGS:

Written by Paul Robinson

A Web coder in languages such as CSS, X/HTML, jQuery, but mostly PHP. Addicted to Girls Aloud, Jennifer Morrison, Carah Faye Charnow, TV Show Chuck, and completely in love with Yvonne Strahovski's smile.

Give something back!

If you LOVED this tutorial and would like to show your appreciation, please consider or a little something from our Amazon Wishlist.

Discussion: 2 Comments

  1. Jul 28th, 2009 @ 15:20:07

    Thanks, finally got my head around the tenary operators…


  2. Jul 28th, 2009 @ 15:25:47

    No problem. They take a little while to get round, but they are worth it. :)


Leave a comment

Please enclose code in [lang] tags. For example [php] echo 'hello world'; [/php]

* Name, Email, Comment are Required