Introduction
While and do-while loops in PHP allow you to execute a block of code repeatedly as long as a condition is satisfied. They are useful for counting numbers, calculating totals, processing records, and repeating tasks until a condition changes. In this chapter, you will practise both loops through solved PHP questions, with working code, sample outputs, and beginner-friendly explanations to help you understand how each loop works. PHP While and Do-While Loops Practice questions with solutions to help you understand the concepts.
Question 1: Print Numbers from 1 to 10 Using a While Loop
Problem Statement:
Write a PHP program to print numbers from 1 to 10 using a while loop.
PHP Solution
<?php
$num = 1;
while ($num <= 10) {
echo $num . " ";
$num++;
}
?>
Sample Output
1 2 3 4 5 6 7 8 9 10
Explanation
- The variable
$numstarts at1. - The
whileloop checks whether$numis less than or equal to10. - If the condition is true, the number is printed.
$num++increases the number by one after each iteration.- The loop stops when
$numbecomes11.
Concepts Covered
whileloop in PHP- Loop condition
- Increment operator
- Repeated execution
Question 2: Print Even Numbers from 2 to 20
Problem Statement:
Write a PHP program to display all even numbers from 2 to 20 using a while loop.
PHP Solution
<?php
$num = 2;
while ($num <= 20) {
echo $num . " ";
$num += 2;
}
?>
Sample Output
2 4 6 8 10 12 14 16 18 20
Explanation
The variable $num starts at 2. Because adding 2 keeps the number even, the loop prints only even numbers. The loop continues while $num is less than or equal to 20.
The statement $num += 2 is a shorter way of writing $num = $num + 2.
Concepts Covered
whileloop in PHP- Even numbers
- Assignment operators
- Incrementing by two
Question 3: Calculate the Sum of Numbers from 1 to 100
Problem Statement:
Write a PHP program to calculate the sum of all integers from 1 to 100 using a while loop.
PHP Solution
<?php
$num = 1;
$sum = 0;
while ($num <= 100) {
$sum += $num;
$num++;
}
echo "Sum = " . $sum;
?>
Sample Output
Sum = 5050
Explanation
The variable $sum stores the running total and starts at 0. During every iteration, the current value of $num is added to $sum. The number is then increased by one.
When the loop finishes, $sum contains the total of all numbers from 1 to 100.
Concepts Covered
whileloop in PHP- Running total
- Accumulator variable
- Addition and increment operators
Question 4: Print a Multiplication Table Using a While Loop
Problem Statement:
Write a PHP program to display the multiplication table of 7 from 1 to 10.
PHP Solution
<?php
$num = 7;
$i = 1;
while ($i <= 10) {
echo $num . " x " . $i . " = " . ($num * $i) . "<br>";
$i++;
}
?>
Sample Output
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
Explanation
The variable $num stores the number whose table is required. The variable $i starts at 1 and increases until it reaches 10.
In each iteration, the program multiplies $num by $i and displays the result. The HTML <br> tag puts each result on a new line when the code runs in a browser.
Concepts Covered
whileloop in PHP- Multiplication
- Loop counter
- Displaying output in a browser
Question 5: Print Numbers from 10 to 1 Using a Do-While Loop
Problem Statement:
Write a PHP program to display numbers from 10 down to 1 using a do-while loop.
PHP Solution
<?php
$num = 10;
do {
echo $num . " ";
$num--;
} while ($num >= 1);
?>
Sample Output
10 9 8 7 6 5 4 3 2 1
Explanation
A do-while loop executes its body before checking the condition. The program prints the current number and decreases it by one using $num--.
The loop continues while $num is greater than or equal to 1. When $num becomes 0, the condition is false and the loop stops.
Notice that a do-while loop ends with a semicolon after its condition.
Concepts Covered
do-whileloop- Decrement operator
- Reverse counting
- Loop termination condition
Question 6: Display a Message at Least Once Using a Do-While Loop
Problem Statement:
Write a PHP program that displays a message once, even when the loop condition is initially false.
PHP Solution
<?php
$num = 10;
do {
echo "Welcome to PHP Loops!";
$num++;
} while ($num <= 5);
?>
Sample Output
Welcome to PHP Loops!
Explanation
The variable $num starts at 10, so the condition $num <= 5 is false from the beginning.
However, a do-while loop executes its body before checking the condition. Therefore, the message appears once. After the body executes, $num becomes 11, the condition is checked, and the loop stops.
This is an important difference between while and do-while loops.
Concepts Covered
do-whileloop- False initial condition
- Condition checking
- Minimum one execution
Question 7: Calculate the Factorial of a Number
Problem Statement:
Write a PHP program to calculate the factorial of 5 using a while loop.
The factorial of 5 is:
5 × 4 × 3 × 2 × 1 = 120
PHP Solution
<?php
$num = 5;
$i = 1;
$factorial = 1;
while ($i <= $num) {
$factorial *= $i;
$i++;
}
echo "Factorial of " . $num . " = " . $factorial;
?>
Sample Output
Factorial of 5 = 120
Explanation
The variable $factorial starts at 1 because multiplying by 1 does not change the result.
The loop multiplies $factorial by each integer from 1 to 5. After the final iteration, the factorial is 120.
Starting the factorial variable at 0 would make the final result 0, because any number multiplied by zero is zero.
Concepts Covered
whileloop- Factorial calculation
- Multiplication
- Accumulator variable
Question 8: Calculate the Average of Student Marks
Problem Statement:
A teacher has marks for five students. Write a PHP program to calculate their average using a while loop.
PHP Solution
<?php
$marks = [75, 80, 85, 90, 70];
$i = 0;
$total = 0;
$count = count($marks);
while ($i < $count) {
$total += $marks[$i];
$i++;
}
$average = $total / $count;
echo "Total Marks = " . $total . "<br>";
echo "Average Marks = " . $average;
?>
Sample Output
Total Marks = 400
Average Marks = 80
Explanation
The marks are stored in an array. PHP arrays use indexes starting at 0, so the five marks have indexes from 0 to 4.
The while loop adds each mark to $total. The count() function returns the number of marks in the array. After the loop finishes, the program divides the total by the number of students to calculate the average.
Concepts Covered
whileloop- Arrays and array indexes
count()function- Total and average calculations
Question 9: Find the Total Sales Using a Do-While Loop
Problem Statement:
A company records sales for five days. Write a PHP program to calculate total sales using a do-while loop.
| Day | Sales |
|---|---|
| Monday | 5000 |
| Tuesday | 7000 |
| Wednesday | 6000 |
| Thursday | 8000 |
| Friday | 9000 |
PHP Solution
<?php
$sales = [5000, 7000, 6000, 8000, 9000];
$i = 0;
$totalSales = 0;
$count = count($sales);
do {
$totalSales += $sales[$i];
$i++;
} while ($i < $count);
echo "Total Sales = " . $totalSales;
?>
Sample Output
Total Sales = 35000
Explanation
The program stores the daily sales figures in an array. The do-while loop adds each sales amount to $totalSales and increases the index by one.
The loop continues while the index is less than the number of sales entries. When all five entries have been processed, the program displays the total sales.
This example assumes the array contains at least one sales entry, because a do-while loop always executes once.
Concepts Covered
do-whileloop- Arrays
- Sales calculations
- Total accumulation
- Array length using
count()
Question 10: Count Employees with Salaries Above ₹30,000
Problem Statement:
A company stores employee salaries in an array. Write a PHP program to count how many employees earn more than ₹30,000 using a while loop.
PHP Solution
<?php
$salaries = [25000, 35000, 42000, 28000, 50000, 30000];
$i = 0;
$count = count($salaries);
$employeeCount = 0;
while ($i < $count) {
if ($salaries[$i] > 30000) {
$employeeCount++;
}
$i++;
}
echo "Employees earning above 30000 = " . $employeeCount;
?>
Sample Output
Employees earning above 30000 = 3
Explanation
The loop checks each salary in the array. If a salary is greater than 30000, the variable $employeeCount increases by one.
The salaries 35000, 42000, and 50000 meet the condition. A salary of exactly 30000 does not qualify because the condition uses the > operator rather than >=.
Concepts Covered
whileloop- Arrays
ifstatement inside a loop- Comparison operators
- Counting matching records
Key Takeaways
- A
whileloop checks its condition before executing the loop body. - A
do-whileloop executes the loop body before checking the condition. - A
whileloop can execute zero times if its condition is initially false. - A
do-whileloop executes at least once. - Use increment (
++) and decrement (--) operators to update loop counters. - Use accumulator variables to calculate totals, averages, and factorials.
- Arrays can be processed using loops and array indexes.
- The
count()function returns the number of elements in an array. - Always make sure the loop condition can eventually become false to avoid an infinite loop.
- A
do-whilestatement requires a semicolon after its final condition.
Frequently Asked Questions (FAQs)
1. What is a while loop in PHP?
A while loop repeatedly executes a block of code as long as its condition is true. PHP checks the condition before every iteration.
2. What is a do-while loop in PHP?
A do-while loop executes a block of code first and checks the condition afterward. Therefore, its body executes at least once.
3. What is the main difference between while and do-while loops?
A while loop checks the condition before executing its body, whereas a do-while loop checks the condition after executing its body.
4. Can a while loop execute zero times?
Yes. If its condition is false before the first iteration, the loop body does not execute.
5. Can a do-while loop execute more than once?
Yes. It continues executing as long as its condition remains true. It executes only once when the condition becomes false after the first iteration.
6. Why is an increment or decrement operator used in loops?
These operators update a counter. For example, $i++ increases $i by one, while $i-- decreases it by one.
7. What happens if a loop condition never becomes false?
The loop may become an infinite loop, repeatedly executing its body. To prevent this, update the relevant variables or ensure the condition can eventually become false.
8. Can a while loop be used with PHP arrays?
Yes. A while loop can access array elements using their indexes and process each element. The count() function can help determine how many elements need to be processed.
9. Is a semicolon required after a do-while loop?
Yes. PHP requires a semicolon after the final while condition of a do-while statement.
10. When should I use a while loop instead of a do-while loop?
Use a while loop when the code should run only if a condition is true before the first iteration. Use a do-while loop when the code must execute at least once before the condition is checked.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
