✍️

PHP Control Flow Explained: If Else, Switch, For Loop, While, Do While & Foreach with Examples

```html PHP Control Flow Explained: If Else, Switch, Loops & Foreach

PHP Control Flow Explained

If Else, Switch, For, While, Do While & Foreach with Real-Life Examples

Introduction

When writing a PHP program, we often need to make decisions or repeat certain tasks. For example, checking whether a user can log in, deciding whether a student is pass or fail, printing numbers from 1 to 100, or displaying products in an online store.

This is where Control Flow comes into play. Control Flow decides the order in which PHP code runs. It allows PHP programs to make decisions, choose different paths, and repeat code when required.

In simple words: Control Flow means controlling how your program runs.

What is Control Flow?

Control Flow is the mechanism that controls the execution of a program based on conditions and loops.

Control Flow has two major categories:

  1. Decision Making Statements
    • if
    • if...else
    • if...elseif...else
    • switch
  2. Looping Statements
    • for
    • while
    • do...while
    • foreach

1. The if Statement

The if statement executes a block of code only when a specified condition is true.

Syntax

if(condition){
    // code
}

Example

<?php

$age = 20;

if($age >= 18){
    echo "Eligible to Vote";
}

?>

Output

Eligible to Vote
Real-Life Example: Imagine entering a movie theatre. If your age is 18 or above, entry is allowed. Otherwise, entry is denied.
Use Cases:
  • User authentication
  • Login verification
  • OTP validation
  • Age verification
  • Product availability checks

2. The if...else Statement

The if...else statement is used when there are two possible outcomes. If the condition is true, the if block runs. Otherwise, the else block runs.

<?php

$marks = 35;

if($marks >= 40){
    echo "Pass";
}else{
    echo "Fail";
}

?>
Real-Life Example: In online payment, if payment is successful, show “Order Confirmed”. Otherwise, show “Transaction Failed”.
Use Cases:
  • Pass or Fail result
  • Login success or failure
  • Payment success or failure
  • Product in stock or out of stock

3. The if...elseif...else Statement

When multiple conditions need to be checked, we use if...elseif...else. It is useful when a program has more than two possible results.

<?php

$score = 82;

if($score >= 90){
    echo "Grade A+";
}
elseif($score >= 75){
    echo "Grade A";
}
elseif($score >= 60){
    echo "Grade B";
}
else{
    echo "Grade C";
}

?>
Real-Life Example: In a college grading system, students get grades based on marks: 90+ means A+, 75–89 means A, 60–74 means B, and below 60 means C.
Use Cases:
  • Student grading
  • Salary slabs
  • Income tax calculation
  • Membership levels
  • Scholarship eligibility

4. The switch Statement

The switch statement compares one variable with multiple possible values. It is cleaner than writing many if...elseif conditions.

<?php

$day = "Sunday";

switch($day){

    case "Sunday":
        echo "Holiday";
        break;

    case "Monday":
        echo "Working Day";
        break;

    default:
        echo "Normal Day";
}

?>
Important: The break statement stops the switch after a matching case.
Real-Life Example: ATM menu:
  • 1 → Withdraw Money
  • 2 → Deposit Money
  • 3 → Check Balance
  • 4 → Mini Statement
Use Cases:
  • ATM menus
  • Language selection
  • Theme selection
  • Navigation menus
  • Day or month identification

5. The for Loop

A for loop is used when the number of repetitions is already known. It is commonly used for counting and fixed repeated tasks.

<?php

for($i = 1; $i <= 5; $i++){
    echo $i . "<br>";
}

?>

Output

1
2
3
4
5
Real-Life Example: A teacher wants to print roll numbers from 1 to 50. Instead of writing 50 print statements, a for loop can do it automatically.
Use Cases:
  • Multiplication tables
  • Number patterns
  • Pagination
  • Sending bulk emails
  • Repeating tasks a fixed number of times

6. The while Loop

The while loop continues executing as long as the condition remains true. It is useful when we do not know exactly how many times the loop will run.

<?php

$i = 1;

while($i <= 5){
    echo $i . "<br>";
    $i++;
}

?>
Real-Life Example: While a file download is not complete, keep downloading. The process stops only after the download is complete.
Use Cases:
  • Reading database records
  • Processing queues
  • Polling APIs
  • Unknown number of iterations

7. The do...while Loop

The do...while loop executes the code block first and checks the condition afterward. This means the loop runs at least once.

<?php

$i = 1;

do{
    echo $i . "<br>";
    $i++;
}
while($i <= 5);

?>
Real-Life Example: An ATM always displays the menu once before asking whether you want another transaction. Even if you exit immediately, the menu appears at least once.
Use Cases:
  • ATM systems
  • Menu-driven programs
  • Retry mechanisms
  • Input validation

8. The foreach Loop

The foreach loop is specially designed for arrays. It automatically visits every element without using an index.

<?php

$fruits = ["Apple", "Banana", "Mango"];

foreach($fruits as $fruit){
    echo $fruit . "<br>";
}

?>
Real-Life Example: An e-commerce website has many products. Instead of displaying every product manually, foreach loops through the product list and displays each item.
Use Cases:
  • Product listings
  • Student records
  • Shopping carts
  • Employee lists
  • API responses
  • Database result sets

Comparison of All Statements

Statement Purpose Best Use Case
if Check one condition Login validation
if...else Two possible outcomes Pass/Fail
if...elseif...else Multiple conditions Grading system
switch Match one value against many cases Menus and navigation
for Known number of repetitions Tables and counters
while Repeat while condition is true Downloads and queues
do...while Execute at least once ATM menus
foreach Traverse arrays Product or user lists

Practical Scenario: Online Shopping Website

Suppose you are building an online shopping website:

  • if → Check whether the user is logged in.
  • if...else → Determine if payment succeeded or failed.
  • if...elseif...else → Apply discounts based on order value.
  • switch → Choose payment method such as UPI, Card, or COD.
  • for → Generate invoice line numbers.
  • while → Process pending orders until none remain.
  • do...while → Keep asking for coupon codes until the user exits.
  • foreach → Display all products in the shopping cart.

Practice Questions

  1. Write a program to check whether a number is positive or negative using if...else.
  2. Create a grading system using if...elseif...else.
  3. Display the weekday name using a switch statement.
  4. Print numbers from 1 to 20 using a for loop.
  5. Print even numbers between 2 and 50 using a for loop.
  6. Use a while loop to print numbers from 10 to 1.
  7. Write a do...while loop that prints numbers from 1 to 5.
  8. Create an array of five programming languages and print them using foreach.
  9. Print the multiplication table of 8 using a for loop.
  10. Calculate the sum of numbers from 1 to 100 using any loop.

Mini Quiz

Q1. Which loop always executes at least once?

Answer: do...while

Q2. Which loop is best for arrays?

Answer: foreach

Q3. Which statement is cleaner for checking multiple fixed values?

Answer: switch

Q4. Which loop is best when the number of iterations is known?

Answer: for

Q5. Which statement is commonly used for login validation?

Answer: if

Conclusion

Control Flow is the backbone of PHP programming. It enables applications to make decisions, repeat tasks, and process data efficiently. Whether you are building a login system, an online shopping platform, a student portal, or a banking application, you will use if, switch, and loops extensively.

By mastering these concepts and practicing real-world examples, you will be ready to build dynamic PHP applications and answer interview questions with confidence.

```
❮ Previous Next ❯