Tutorials

Learn web design and programming with our free video and text tutorials.

PHP if, else and else if Conditional Statements

PHP if, if...else and else...if conditional statements are used to perform different actions if certain conditions are met.

PHP if statements

The if statement executes a set of code immediately following the condition that is specified it is true.

<?php
$number = 5;
if ($number < 10)
echo "5 is less than 10.";
?>

The code above outputs:

5 is less than 10.

The code outputs "5 is less than 10." because the condition is true.

<?php
$number = 5;
if ($number < 4)
echo "5 is less than 4.";
?>

The code above outputs:

Because the condition given is not true, there is nothing output.

If there will be more than one statement following the if keyword which is followed parenthesis (()), you will need to enclose the statements in brackets ({}). For single statements, the use of the brackets is optional.

<?php
$number = 5;
if ($number < 10)
{
echo "5 is less than 10.<br />";
echo "5 is my lucky number.<br />";
echo "It is also my favorite number.";
}
?>

The code above outputs:

5 is less than 10.
5 is my lucky number.
It is also my lucky number.

PHP if...else statements

PHP if...else statements execute a set of code immediately following the condition if it is true and another set of code if the condition is false.

<?php
$number = 5;
if ($number < 10)
{
echo "5 is less than 10";
}
else
{
echo "5 is less than 10 is not true";
}
?>

The code above outputs:

5 is less than 10

PHP elseif statements

The elseif keyword can be used to add more conditions that are checked only if the previous condition in the statement is not true.

<?php
$number = 10;
if ($number < 10)
{
echo "the variable \$number is less than 10";
}
elseif ($number == 10)
{
echo "the variable \$number is equal to 10";
}
else
{
echo "the variable \$number is less than 10 is not true";
}
?>

The code above outputs:

the variable $number is equal to 10

Notice that the == (equal to) operator and not the = (assignment) operator is used in the elseif statement. This checks the wether the left and right values are equal and does not assign a new value to the variable.