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.
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:
-
Decision Making Statements
- if
- if...else
- if...elseif...else
- switch
-
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
- 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";
}
?>
- 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";
}
?>
- 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";
}
?>
break statement stops the switch after a matching case.
- 1 → Withdraw Money
- 2 → Deposit Money
- 3 → Check Balance
- 4 → Mini Statement
- 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
- 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++;
}
?>
- 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);
?>
- 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>";
}
?>
- 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
- Write a program to check whether a number is positive or negative using if...else.
- Create a grading system using if...elseif...else.
- Display the weekday name using a switch statement.
- Print numbers from 1 to 20 using a for loop.
- Print even numbers between 2 and 50 using a for loop.
- Use a while loop to print numbers from 10 to 1.
- Write a do...while loop that prints numbers from 1 to 5.
- Create an array of five programming languages and print them using foreach.
- Print the multiplication table of 8 using a for loop.
- 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.