WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

PHP if...else...elseif Statements

Condition statements are used to perform different actions based on different conditions.


PHP conditional statement

When you write code, you often need to perform different actions for different judgments. You can use conditional statements in your code to accomplish this task.

In PHP, the following conditional statements are provided:

  • if statement -execute code when condition is satisfied
  • if ... else statement -execute one piece of code when the condition is true, and another piece of code when the condition is not true
  • if ... elseif .... else statement -execute a block of code when one of several conditions is true
  • switch statement -execute a block of code when one of several conditions is true

PHP - The if Statement

The if statement is used to execute code only when the specified condition is true.

Syntax

if (condition)
{
    The code to execute when the condition is true;
}

If the current time is less than 20, the following example will output "Have a good day!":

Examples

<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } ?>


PHP - The if...else Statement

Execute one piece of code when the condition is true, and another piece of code when the condition is not true. Use an if .... else statement.

Syntax

if ( condition )
{
Code executed when the condition is met;
}
else
{
Code executed when the condition is not satisfied;
}

If the current time is less than 20, the example below will output "Have a good day!", otherwise it will output "Have a good night!":

Examples

<?php $t=date("H"); if ($t<"20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?>


PHP-if ... elseif .... else statements

Execute a block of code when one of several conditions is true , use if .... elseif ... else statements. .

Syntax

if (condition)
{
    if Code executed when the condition is met;
}
elseif (condition)
{
    elseif Code executed when the condition is met;
}
else
{
    Code executed when the condition is not met;
}

If the current time is less than 10, the following example will output "Have a good morning!", if the current time is not less than 10 and less than 20, then "Have a good day!", otherwise "Have a good night!" ":

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!"; } ?>