PHP if statement syntax

Home -> Programming -> Web -> PHP

53224 views

From the computer of: qmchenry (338 recipes)
Created: Dec 27, 2003     Updated: Jun 19, 2006


Add a comment

Add to:
Add to stumbleuponAdd to del.icio.usDigg itAdd to FURL







The simplest if statement executes command(s) if a condition evaluates as true:

if ($var > 0 ) {
     // code here run if $var is positive
     echo "Square root is: ".sqrt($var);
}


An optional else block can be added to execute code if the test condition evaluates as false. Multiple lines of code must be enclosed within { braces } while a single statement can be used in an if statement without braces.

if ($var >= 0 )
    echo "Square root is: ".sqrt($var);
else {
    $negvar = -1*$var;
    echo "Square root is: ".sqrt($var)."i";
}


If statements can be nested:

if ($var < 10)
    echo "var is less than 10";
elseif ($var < 20)
    echo "var is between 10 and 20";
elseif ($var < 30)
    echo "var is between 20 and 30";
else
    echo "var is greater than 30";



A compact (if cryptic) shorthand is useful:

echo "var is ".($var < 0 ? "negative" : "positive");


is equivalent to:

echo "var is ";
if ($var < 0)
    echo "negative";
else
    echo "positive";


The shorthand can be considered (expression ? true_value : false_value) where 'expression' is evaluated and, if true, the 'true_value' is returned, otherwise the 'false_value' is returned.

Subscribe to the Tech-Recipes Newsletter

You can get tips like this delivered in your email every week!

Enter your Email

We will never, ever sell your email address or spam you.





Related recipes:

  PHP conditional syntax: using switch and case statements
  PHP syntax: comments
  Solve PHP error: Cannot modify header information - headers already sent
  PHP syntax: for loop basics
  PHP: Rename or move a file on the server
  PHP conditional syntax: inequality
  PHP: Password Protect Your pages.
  PHP syntax: iterate over an associative array
  PHP conditional syntax: less than
  PHP syntax: create an associative array

 

Sponsored links

 

Login

Nickname

Password

Don't have an account yet? You can create one. As a registered user you have some advantages like theme manager, comments configuration and post comments with your name.