Tip of the day: PHP short-hand IF statement

Posted By Scott Klarr on Jan 10, 2008 at 5:16 pm

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 post has the following tags:

Related Links

Comments (1)

Freddy - Apr 03, 2008

FYI this is called a 'ternary' comparision

Post Comment

Your Name
Email Address
Website URL
Comment

Your email address will not be visible to the public

page counter

Loading Ad