-
Hajipur, Bihar, 844101
In programming, you often need to repeat certain tasks — like displaying a list of students, calculating totals, or processing records from a database. Writing the same code multiple times isn’t efficient. That’s where loops come in.
A loop allows you to run a block of code multiple times automatically, until a specific condition is met. In PHP, loops are essential for handling repetitive tasks quickly and neatly.
Imagine you want to print numbers from 1 to 100. Without loops, you’d have to write 100 echo
statements — clearly not practical.
With loops, you can do it with just a few lines of code:
<?php
for ($i = 1; $i <= 100; $i++) {
echo $i . " ";
}
?>
That’s the power of loops — automating repetition efficiently.
PHP provides four main types of loops, each suited for a specific use case:
while
loop – Repeats as long as a condition is true.
do...while
loop – Runs the code once before checking the condition.
for
loop – Used when you know how many times to run the loop.
foreach
loop – Special loop used for arrays.
Let’s go through each in detail.
The while loop executes a block of code as long as the given condition is true.
while (condition) {
// Code to be executed
}
<?php
$count = 1;
while ($count <= 5) {
echo "Count is: $count <br>";
$count++;
}
?>
Explanation:
PHP checks the condition $count <= 5
.
If it’s true, the code block runs.
The variable $count
increases by 1 each time.
When $count
becomes 6, the loop stops.
Output:
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Use a while
loop when you don’t know exactly how many times the code should run (for example, reading data until the end of a file).
The do...while loop is similar to the while
loop, except it executes the code at least once, even if the condition is false.
do {
// Code to execute
} while (condition);
<?php
$number = 1;
do {
echo "Number: $number <br>";
$number++;
} while ($number <= 5);
?>
Difference:
In do...while
, the code runs first, then the condition is checked.
So even if $number
started greater than 5, it would still print once.
The for loop is used when you know beforehand how many times the loop should execute.
for (initialization; condition; increment/decrement) {
// Code to execute
}
<?php
for ($i = 1; $i <= 10; $i++) {
echo "The number is: $i <br>";
}
?>
Explanation:
$i = 1
→ The loop starts with 1.
$i <= 10
→ The loop continues as long as this condition is true.
$i++
→ After each iteration, $i
increases by 1.
Output:
The number is: 1
The number is: 2
...
The number is: 10
This loop is best for counting, printing sequences, and handling known ranges of data.
The foreach loop is specifically designed for arrays. It lets you loop through each item in an array without worrying about indexes.
foreach ($array as $value) {
// Code to execute
}
Or, if you want both key and value:
foreach ($array as $key => $value) {
// Code to execute
}
<?php
$students = ["Vicky", "Sanjana", "Vrinda", "Riya"];
foreach ($students as $name) {
echo "Student: $name <br>";
}
?>
Output:
Student: Vicky
Student: Sanjana
Student: Vrinda
Student: Riya
Example with keys:
<?php
$marks = [
"Vicky" => 90,
"Sanjana" => 85,
"Vrinda" => 78
];
foreach ($marks as $student => $score) {
echo "$student scored $score marks. <br>";
}
?>
The foreach
loop is heavily used when working with arrays, JSON data, or database results.
You can use a loop inside another loop — this is called a nested loop.
Useful for working with multi-dimensional arrays or tables.
<?php
for ($i = 1; $i <= 3; $i++) {
for ($j = 1; $j <= 3; $j++) {
echo "($i, $j) ";
}
echo "<br>";
}
?>
Output:
(1, 1) (1, 2) (1, 3)
(2, 1) (2, 2) (2, 3)
(3, 1) (3, 2) (3, 3)
Nested loops are commonly used for grids, tables, and structured data like seating plans or calendars.
Sometimes you need to stop a loop early or skip certain iterations. PHP gives you two control keywords for this: break
and continue
.
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 5) {
break;
}
echo $i . " ";
}
?>
Output:
1 2 3 4
Here, the loop stops completely when $i
becomes 5.
<?php
for ($i = 1; $i <= 5; $i++) {
if ($i == 3) {
continue;
}
echo $i . " ";
}
?>
Output:
1 2 4 5
The continue
statement skips only the current iteration and moves to the next one.
If the condition in a loop never becomes false, the loop runs forever — that’s called an infinite loop.
Be careful with these as they can crash your program.
Example:
<?php
while (true) {
echo "This will run forever!";
}
?>
Always make sure your loop has a clear exit condition.
Let’s use a loop in a simple practical example.
<?php
$marks = [80, 75, 92, 68, 88];
$total = 0;
foreach ($marks as $score) {
$total += $score;
}
$average = $total / count($marks);
echo "Total Marks: $total <br>";
echo "Average Marks: $average";
?>
Output:
Total Marks: 403
Average Marks: 80.6
This kind of logic is common in student report systems, sales summaries, and data analytics.
Forgetting to update the loop variable
Causes infinite loops.
Using wrong conditions
(<=
instead of <
or vice versa) can skip or overcount iterations.
Modifying an array while looping
Avoid changing array structure during a foreach
.
Heavy operations inside loops
Move calculations outside the loop for better performance.
Always make sure your loop condition ends logically.
Use for
when you know the exact count.
Use while
when the end depends on data or user input.
Prefer foreach
for arrays — it’s clean and safe.
Keep loops efficient; avoid unnecessary work inside them.
Loops are used to execute repetitive code automatically.
PHP has four main loops: while
, do...while
, for
, and foreach
.
Use break
to stop a loop and continue
to skip one iteration.
Be careful of infinite loops by managing conditions properly.
Loops make your PHP programs more efficient, organized, and scalable.
By mastering loops, you’ll handle repetitive tasks in your PHP projects with ease — whether it’s displaying records, calculating totals, or processing data dynamically.
Write a PHP program using a for
loop to print numbers from 1 to 50.
Create a PHP script using a while
loop to print all even numbers between 1 and 20.
Write a PHP program using a do...while
loop to display numbers from 10 down to 1.
Create a PHP foreach
loop to print all names from an array of student names.
Write a PHP program using nested for
loops to display a 5x5 multiplication table.
Create a PHP script using break
to stop a loop when a number divisible by 7 is found between 1 and 20.
Write a PHP program using continue
to skip printing numbers divisible by 3 between 1 and 15.
Create a PHP for
loop that prints only odd numbers between 1 and 25.
Write a PHP program to calculate the sum of all elements in an array using a foreach
loop.
Create a PHP program using nested loops to print a right-angled triangle pattern of asterisks with 5 rows.