PHP If...Else
Statements
Conditional statements are used to perform different actions based on different conditions.
PHP Conditional Statements
When writing code, you often need to perform different actions for different decisions. You can use conditional statements in your code to accomplish this.
PHP provides the following conditional statements:
- if statement - Executes code if a condition is true
- if...else statement - Executes one block of code if a condition is true, and another block if it is false
- if...elseif....else statement - Executes one block of code if one of several conditions is true
- switch statement - Executes one block of code if one of several conditions is true
PHP - if Statement
The if statement is used to execute code only if the specified condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
The following example will output "Have a good day!" if the current time is less than 20:
Example
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
?>
PHP - if...else Statement
To execute one block of code if a condition is true and another block if a condition is false, use the if....else statement.
Syntax
The following example will output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
Example
<?php
$t = date("H");
if ($t < "20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
PHP - if...elseif....else Statement
To execute one block of code if one of several conditions is true, use the if....elseif...else statement.
Syntax
if (condition)
{
code to be executed if condition is true;
}
elseif (condition)
{
code to be executed if elseif condition is true;
}
else
{
code to be executed if none of the above conditions are true;
}
The following example will output "Have a good morning!" if the current time is less than 10, "Have a good day!" if the current time is between 10 and 20, and "Have a good night!" otherwise:
Example
<?php
$t = date("H");
if ($t < "10")
{
echo "Have a good morning!";
}
elseif ($t < "20")
{
echo "Have a good day!";
}
else
{
echo "Have a good night!";
}
?>
PHP - switch Statement
The switch statement will be explained in the next chapter.