Skip to main content

The else Statement

Pair an if with else when you also want something to happen if the condition turns out to be false.

If Else

The script greets you according to the current hour: before 20 you see "Have a good day!", and from 20 onwards you see "Have a good night!":

Prompt
Write a PHP script that checks if the current hour is less than 20 and outputs a greeting for day or night accordingly.
Output: PHP script

Syntax

An if...else statement has this form:

index.php
<?php
if (condition) {
  // code to be executed if condition is true;
} else {
  // code to be executed if condition is false;
}
?>

The elseif Statement

Two outcomes are not always enough. For more than two conditions, add elseif, which, as its name suggests, combines if and else: it is tested only when the conditions before it were false.

If Elseif Else

The greeting now has three possibilities. Before hour 10 it is "Have a good morning!", before hour 20 it is "Have a good day!", and later than that it is "Have a good night!":

Prompt
Write a PHP script that uses if, elseif, and else to output different greetings based on the current hour of the day.
Output: PHP script

Syntax

Adding an elseif gives this if...elseif...else form:

index.php
<?php
if (condition) {
  // code to be executed if this condition is true;
} elseif (condition) {
  // code to be executed if first condition is false and this condition is true;
} else {
  // code to be executed if all conditions are false;
}
?>

Multiple elseif

There is no limit on the number of elseif blocks in one statement.

Multiple Elseif Example

Here each weekday gets its own message, and the final else covers the weekend:

Prompt
Write a PHP script that uses multiple elseif statements to check the day of the week and output a message for each day.
Output: PHP script