In this tutorial, we’ll explore the various ways in which decisions can be created within a PHP program using conditional statements.

What are Conditional Statements in PHP?

Conditional statements in PHP are used to make decisions. With the help of conditional statements, you can write code that executes actions depending on whether a specific condition evaluates to true or false.

PHP has several different types of conditional statements, such as:

  • IF statement
  • ELSE IF statement
  • ELSE statement

PHP IF Statement

The IF statement executes a block of code only if a given condition evaluates to true. Here’s an example:

$grade = 95;

if ($grade >= 50){
    echo "You've passed the subject!";
}

When the above code is executed, it produces the following result:

You've passed the subject!

Therefore, in the above code, the test condition was $grade >= 50. Since the grade was initialized to 95, the test condition evaluated to TRUE and the program executed the code within the IF block.

PHP ELSE IF Statement

The ELSE IF statement in PHP allows you to write blocks of code for multiple conditions. The ELSE IF statement is checked only if the previous condition evaluated to false.

Let’s look at an example:

$number = 3;
if ($number == 1) {
    echo "Number 1";
} else if ($number == 2) {
   echo "Number 2";
} else if ($number == 3) {
   echo "Number 3";
}

Output:

Number 3

In the above example, the program checks all the conditional statements until it reaches the last ELSE IF statement which evaluates to TRUE thereby executing the block of code within it.

PHP ELSE Statement

The ELSE statement in PHP is executed only when all the previous conditions evaluated to false. The ELSE statement doesn’t take any condition and will always execute if all the chain of conditions before it were FALSE.

Example:

$number = 25;

if ($number == 1) {
   echo "Number 1";
} else if ($number == 2) {
   echo "Number 2";
} else {
   echo "Your number is " . $number;
}

Output:

Your number is 25

PHP Nested IF Statements

Just like most other programming languages, PHP also allows nested IF statements. This means that you can have multiple conditions within another condition, such as IF…ELSE statement within an IF block.

Nested statements allow programmers to build complex decisions within their programs.

Example:

$number = 0;

if ($number >= 0){
    if ($number == 0){
        echo "The number is zero";
    } else {
        echo "Positive number";
    }
else {
    echo "Negative number";
}

Output:

The number is zero

A program can have multiple nested statements inside one another. However, overusing nested statements may make your code more confusing and may cause logical errors. As such, it must be avoided wherever possible.