osCommerce Home | osCommerce eBook Store | osCommerce Tutorials

PHP If...Else Conditional Statement

The If...Else conditional statement is quite self-explantory. It simply used to perform different actions based on different condition. The if statement is the most widely used conditional statement in all computer programming languages. The if statement is relatively easy to read and understand. The following diagram illustrate the basic structure of a if statement.

PHP If Conditional Statement

The PHP If conditional statement can be used in the following most common ways.

PHP If...Else Example 1:

<?php

$a = 10;
$b = 20;

if ($a > $b) {
echo $a . " is greater than " . $b;
} else {
echo $a . " is smaller than " . $b;
}

?>

The output of the above PHP If...Else example should look like:

10 is smaller than 20

PHP If...Else If Example 2:

<?php

$a = 10;
$b = 20;

if ($a > $b) {
echo $a . " is greater than " . $b;
} else if ($a < $b) {
echo $a . " is surely smaller than " . $b;
}

?>

The output of the above PHP If...Else Ifexample should look like:

10 is surely smaller than 20

PHP If...ElseIf Example 3:

With the latest version of PHP 4 and 5, the If...ElseIf statement is also valid.

<?php

$a = 10;
$b = 20;

if ($a > $b) {
echo $a . " is greater than " . $b;
} elseif ($a < $b) {
echo "Of course. " . $a . " is surely smaller than " . $b;
}

?>

The output of the above PHP If...Else Ifexample should look like:

Of course. 10 is smaller than 20

PHP If...ElseIf...Else Example 4:

<?php

$a = 10;
$b = 10;

if ($a > $b) {
echo $a . " is greater than " . $b;
} elseif ($a < $b) {
echo "Of course. " . $a . " is surely smaller than " . $b;
} else {
echo $a . " is equal to " . $b;
}

?>

The output of the above PHP If...Else Ifexample should look like:

10 is equal to 10

PHP If...ElseIf...Else Example 5:

The following codes are also valid. It seems much easier to read.

<?php

$a = 10;
$b = 10;

if ($a > $b):
echo $a." is greater than ".$b;
elseif ($a < $b):
echo "Of course. ". $a . " is smaller than " . $b;
else:
echo $a . " is surely equal to " . $b;
endif;

?>

The output of the above PHP If...Else Ifexample should look like:

10 is surely equal to 10