Latest web development tutorials

PHP If ... Else Statements

Conditional statement used to perform different actions based on different conditions.


PHP conditional statements

When you write code, you often need to perform different actions for different judgment. You can do this using conditional statements in the code.

In PHP, we provide the following conditional statement:

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

PHP - if statement

if statement is used to execute code only when a specified condition is met.

grammar

if (条件)
{
	条件成立时要执行的代码;
}

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

Running instance »


PHP - if ... else statement

Execute a block of code when condition is met, another piece of code execution condition is not satisfied, use the if .... else statement.

grammar

if (条件)
{
条件成立时执行的代码;
}
else
{
条件不成立时执行的代码;
}

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

Examples

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

Running instance »


PHP - if ... else if .... else statement

Execute a block of code if one of several conditions, use the if .... else if ... else statement. .

grammar

if (条件)
{
if 条件成立时执行的代码;
}
else if (条件)
{
elseif 条件成立时执行的代码;
}
else
{
条件不成立时执行的代码;
}

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, the output, otherwise the output "Have a good night!" "Have a good day!":

Examples

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

Running instance »


PHP - switch statement

switch statement will explain in the next chapter.