Practice Questions on PHP Loops
Practice problems start with basic number printing. Then, logic-based problems are introduced.
Intermediate problems are introduced to improve control over conditions. Following that, simple explanations of nested loops are given. Finally, solved examples are provided, linking theory with practice.
Basic Level Practice Questions
- Print numbers from 1 to 10 using a for loop.
- Print even numbers from 1 to 20 using a while loop.
- Print numbers from 5 to 1 using a do while loop.
- Print all elements of an array using a foreach loop.
- Print the multiplication table of a given number.
Intermediate Level Practice Questions
- Print odd numbers from 1 to 50.
- Calculate the sum of numbers from 1 to 100 using a loop.
- Calculate the number of elements in an array using a loop.
- Print each character of a string using a loop.
- Terminate the loop if the value becomes 7 using break.
Advanced Level Practice Questions
- Print a star pattern using nested loops.
- Iterate over an associative array and print keys and values.
- Use continue to skip numbers divisible by 3.
- Find the largest number in an array using a loop.
- Reverse an array using a loop.
PHP Loop Practice Examples with Code
1 Print Numbers from 11 to 20
<?php
for ($i = 11; $i <= 20; $i++) {
echo $i . " ";
}
?>
2 Print Even Numbers Using While Loop
<?php
$num = 2;
while ($num <= 20) {
echo $num . " ";
$num += 2;
}
?>
3 Do While Loop Example
<?php
$x = 5;
do {
echo $x . " ";
$x--;
} while ($x >= 1);
?>
4 Foreach Loop with Array
<?php
$fruits = ["Apple", "Banana", "Mango", "Guava"];
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
?>
5 Multiplication Table Using Loop
<?php
$number = 5;
for ($i = 1; $i <= 10; $i++) {
echo $number . " x " . $i . " = " . ($number * $i) . "<br>";
}
?>
6 Using Break in Loop
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i == 7) {
break;
}
echo $i . " ";
}
?>
7 Using Continue in Loop
<?php
for ($i = 1; $i <= 10; $i++) {
if ($i % 3 == 0) {
continue;
}
echo $i . " ";
}
?>
8 Star Pattern Using Nested Loops
<?php
for ($i = 1; $i <= 5; $i++) {
for ($j = 1; $j <= $i; $j++) {
echo "* ";
}
echo "<br>";
}
?>
9 Associative Array Loop
<?php
$student = ["name" => "Amit", "age" => 20, "course" => "PHP"];
foreach ($student as $key => $value) {
echo $key . ": " . $value . "<br>";
}
?>
10 Find Largest Number in Array
<?php
$numbers = [10, 45, 7, 89, 23];
$max = $numbers[0];
for ($i = 1; $i < count($numbers); $i++) {
if ($numbers[$i] > $max) {
$max = $numbers[$i];
}
}
echo "Largest number is " . $max;
?>
Link to PHP Introduction
Link to PHP Syntax and Comments
Link to PHP Variables and Data Types


