Ternary PHP short-hand IF/Else statement

Jan 10, 2008 at 5:16 pm - 2 Comments

Lightweight IF Syntax

Any programmer will agree that the IF/ELSE statements are a fundamental part of any language. The basic syntax is pretty universal between languages but many dont realise that there is a shorthand version that allows switching to be done inline.

The syntax is simply statement ? if-true : if-false

$variable = (statement) ? "return if true" : "return if false"; Compared to if(statement) { $variable = "return this if true"; } else { $variable = "return this if false"; }

As you can see, you save a lot of coding by using this lightweight syntax for simple IF/ELSE statements. It can also be used inline within strings which is where I find the most benefit of using it. Here is an example that has a real world use for a simple output that changes between "there is 1 item", "there are X items", and "there are no items" using multiple statements.

$text = "There ". ($total==1 ? "is 1 item" : "are ".($total == 0 ? "no items" : "$total items") ); Compared to: if($total==0) { $text = "There are no items"; } else if($total==1) { $text = "There is 1 item"; } else if($total > 0) { $text = "There are $total items"; }

This topic has the following tags:

  • Digg
  • Reddit
  • Sphinn
  • del.icio.us
  • Slashdot
  • StumbleUpon
  • Technorati
  • Facebook
  • Mixx
  • Google
  • Live
  • TwitThis
  • YahooMyWeb
  • blinkbits
  • BlinkList
  • blogmarks
  • BlogMemes
  • Blogosphere News
  • Blue Dot
  • Bumpzee
  • Fark
  • Furl
  • IndianPad
  • LinkedIn
  • Ma.gnolia
  • MisterWong
  • Netvouz
  • Propeller
  • description
  • Socialogs
  • SphereIt
  • Blogsvine
  • connotea
  • eKudos
  • IndiaGram
  • LinkaGoGo
  • LinkArena
  • Linkter
  • Meneame
  • NewsVine
  • PlugIM
  • ThisNext

Comments (2)

Freddy's Avatar

Freddy Apr 03, 2008

FYI this is called a 'ternary' comparision

Sean's Avatar

Sean Dec 27, 2008

Thanks for making this so search-able. I've seen this syntax many times before but never paid too close attention to it until I actually wanted to use it - very clear description I appreciate the help.

Post Comment

You are replying to cancel reply

Your email address will not be visible to the public

Avatars by Gravatar. Join Gravatar for free to have your avatar shown everywhere you post.

page counter

Loading Ad