Tuesday, February 7, 2012

PHP if / else if / else Statement Example

IF Statement

If an expression is TRUE then execute a statement.

if (expression) {
    statement;
}


Example
$a = 2;
$b = 4;

if ($a < $b) {   echo 'a is smaller than b'; }
Result
a is smaller than b
But what if the expression is FALSE?

IF, ELSE Statement

If an expression is TRUE do this, if FALSE do that.

if (expression) {
    statement;
} else {
    statement;
}


Example
$a = 6;
$b = 4;

if ($a < $b) {   echo 'a is smaller than b'; } else {   echo 'a is not smaller than b'; }
Result
a is not smaller than b
What if you want to check more than one expression?

IF, ELSE IF, ELSE Statement

Testing multiple expression if TRUE then execute default statement if FALSE

if (expression) {
  statement;
} elseif (expression) {
  statement;
} else {
  statement;
}


Example
$a = 4;
$b = 4;

if ($a < $b) {   echo 'a is smaller than b'; } else if ($a == $b) {   echo 'a equals b'; } else {   echo 'a is not smaller than b'; }
Result
a equals b

No comments:

Post a Comment