0
0
PHPprogramming~5 mins

Why conditional flow is needed in PHP

Choose your learning style9 modes available
Introduction

Conditional flow helps a program decide what to do based on different situations. It makes the program smart by choosing different actions depending on conditions.

When you want to check if a user entered the correct password.
When you want to show a message only if a number is positive.
When you want to perform different tasks based on the day of the week.
When you want to give a discount only if the 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 if checks a condition and runs code only if it is true.

The else runs code if the if condition is false.

Examples
This checks if age is 18 or more and prints a message accordingly.
PHP
<?php
$age = 18;
if ($age >= 18) {
    echo "You can vote.";
} else {
    echo "You are too young to vote.";
}
?>
This decides if the score is passing or failing.
PHP
<?php
$score = 75;
if ($score >= 60) {
    echo "Passed";
} else {
    echo "Failed";
}
?>
Sample Program

This program checks the temperature and prints if it is hot or cool.

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

Always make sure your conditions are clear and simple.

You can add more checks using elseif for multiple choices.

Summary

Conditional flow lets programs make decisions.

It runs different code based on true or false conditions.

This makes programs flexible and useful in real life.