0
0
PHPprogramming~5 mins

If-else execution flow in PHP

Choose your learning style9 modes available
Introduction

If-else helps your program choose what to do based on conditions. It makes decisions like you do in real life.

Deciding if a user can log in based on password correctness.
Checking if a number is positive, negative, or zero.
Choosing a message to show based on the time of day.
Turning on a light if it is dark outside.
Giving discounts only if a customer buys more than 5 items.
Syntax
PHP
<?php
if (condition) {
    // code to run if condition is true
} else {
    // code to run if condition is false
}
?>

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

Only one block runs: either the if part or the else part.

Examples
This checks if age is 18 or more. If yes, it prints a voting message; otherwise, it says you are too young.
PHP
<?php
$age = 18;
if ($age >= 18) {
    echo "You can vote.";
} else {
    echo "You are too young to vote.";
}
?>
This checks if a number is positive. If not, it prints a different message.
PHP
<?php
$number = -5;
if ($number > 0) {
    echo "Positive number.";
} else {
    echo "Not a positive number.";
}
?>
Sample Program

This program checks the temperature. If it is above 25, it says it's hot; otherwise, it says it is not hot.

PHP
<?php
$temperature = 30;
if ($temperature > 25) {
    echo "It's hot outside.";
} else {
    echo "It's not hot outside.";
}
?>
OutputSuccess
Important Notes

You can add more conditions using elseif for multiple choices.

Make sure your conditions are clear and simple to avoid confusion.

Summary

If-else lets your program pick between two paths based on a condition.

Only one block runs: either the if or the else.

Use it to make your program smart and responsive to different situations.