0
0
PHPprogramming~5 mins

If statement execution flow in PHP

Choose your learning style9 modes available
Introduction

An if statement helps your program decide what to do based on a condition. It lets your code choose between different paths.

When you want to check if a user is logged in before showing a page.
When you want to give a discount only if the purchase amount is over a certain value.
When you want to show a message if a form field is empty.
When you want to run different code depending on the time of day.
Syntax
PHP
<?php
if (condition) {
    // code to run if condition is true
} elseif (another_condition) {
    // code to run if the first condition is false and this one is true
} else {
    // code to run if all above conditions are false
}
?>

The condition is a statement that is either true or false.

The elseif and else parts are optional.

Examples
This checks if age is 18 or more, then prints a message.
PHP
<?php
if ($age >= 18) {
    echo "You can vote.";
}
?>
This chooses a grade based on the score using if, elseif, and else.
PHP
<?php
if ($score >= 90) {
    echo "Grade A";
} elseif ($score >= 80) {
    echo "Grade B";
} else {
    echo "Grade C or below";
}
?>
Sample Program

This program checks the temperature and prints a message based on its value.

PHP
<?php
$temperature = 25;
if ($temperature > 30) {
    echo "It's hot outside.";
} elseif ($temperature >= 20) {
    echo "The weather is nice.";
} else {
    echo "It's cold outside.";
}
?>
OutputSuccess
Important Notes

Only one block of code inside the if-elseif-else runs, the first true condition found.

If no condition is true and there is no else, nothing happens.

Summary

If statements let your program choose what to do based on conditions.

Use elseif to check multiple conditions in order.

Use else to run code when no conditions are true.