PHP For Loops Practice Questions with Solutions

Introduction

A for loop in PHP is used to repeat a block of code a specific number of times. It is useful for counting numbers, calculating totals, generating multiplication tables, processing arrays, and creating patterns. A for loop usually contains three parts: initialization, condition, and increment or decrement. In this chapter, you will practise PHP for loops through solved questions, starting with basic counting and progressing to practical calculations. PHP For Loops practice questions with solutions to help you understand the concepts.

Question 1: Print Numbers from 1 to 10 Using a For Loop

Problem Statement

Write a PHP program that prints all numbers from 1 to 10 using a for loop.

PHP Solution

<?php
for ($i = 1; $i <= 10; $i++) {
    echo $i . "\n";
}
?>

Sample Output

1
2
3
4
5
6
7
8
9
10

Explanation

The loop begins by setting $i to 1. The condition $i <= 10 determines whether the loop should continue.

After each iteration, $i++ increases the value by 1. When $i becomes 11, the condition is false, and the loop stops.

Concepts Covered

  • for loop
  • Initialization
  • Loop condition
  • Increment operator
  • Repeated execution

Question 2: Print Even Numbers from 1 to 20

Problem Statement

Write a PHP program that prints all even numbers from 1 to 20 using a for loop.

PHP Solution

<?php
for ($i = 2; $i <= 20; $i += 2) {
    echo $i . "\n";
}
?>

Sample Output

2
4
6
8
10
12
14
16
18
20

Explanation

The loop starts at 2, the first even number. Instead of increasing the counter by 1, $i += 2 increases it by 2 after each iteration.

This means the loop visits only even numbers, so no additional condition is needed to check whether each number is even.

Concepts Covered

  • for loop
  • Increment by 2
  • Even numbers
  • Arithmetic assignment operator
  • Loop control

Question 3: Calculate the Sum of Numbers from 1 to 100

Problem Statement

Write a PHP program that calculates the sum of all integers from 1 to 100 using a for loop.

PHP Solution

<?php
$sum = 0;

for ($i = 1; $i <= 100; $i++) {
    $sum += $i;
}

echo "Sum of numbers from 1 to 100: " . $sum;
?>

Sample Output

Sum of numbers from 1 to 100: 5050

Explanation

The variable $sum starts at 0. During each iteration, the current value of $i is added to $sum.

For example, the first iterations calculate:

  • First iteration: 0 + 1 = 1
  • Second iteration: 1 + 2 = 3
  • Third iteration: 3 + 3 = 6

The process continues until 100 is added. The final sum is 5050.

Concepts Covered

  • for loop
  • Accumulator variable
  • Addition
  • Compound assignment (+=)
  • Running totals

Question 4: Generate a Multiplication Table

Problem Statement

Write a PHP program that displays the multiplication table of 7 from 1 to 10 using a for loop.

PHP Solution

<?php
$number = 7;

for ($i = 1; $i <= 10; $i++) {
    $result = $number * $i;

    echo $number . " x " . $i . " = " . $result . "\n";
}
?>

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 $number stores the number whose table is required.

The loop runs from 1 to 10. In every iteration, PHP multiplies $number by $i and stores the answer in $result.

The echo statement displays each multiplication in a readable format.

You can change $number to 5, 9, 12, or any other number to generate a different table.

Concepts Covered

  • for loop
  • Multiplication
  • Variables
  • Arithmetic expressions
  • String concatenation

Question 5: Calculate the Factorial of a Number

Problem Statement

Write a PHP program that calculates the factorial of a positive integer using a for loop.

For this example, calculate the factorial of 5.

The factorial of 5 is:

5! = 5 × 4 × 3 × 2 × 1 = 120

PHP Solution

<?php
$number = 5;
$factorial = 1;

for ($i = 1; $i <= $number; $i++) {
    $factorial *= $i;
}

echo "Factorial of " . $number . " is " . $factorial;
?>

Sample Output

Factorial of 5 is 120

Explanation

The variable $factorial starts at 1 because multiplying by 1 does not change a number.

The loop multiplies $factorial by every integer from 1 to 5:

  • 1 × 1 = 1
  • 1 × 2 = 2
  • 2 × 3 = 6
  • 6 × 4 = 24
  • 24 × 5 = 120

The final factorial is 120.

Note: This example assumes a non-negative integer. Factorial is defined as 1 for both 0! and 1!.

Concepts Covered

  • for loop
  • Factorial calculation
  • Multiplication
  • Compound assignment (*=)
  • Accumulator variable

Question 6: Print Numbers in Reverse Order

Problem Statement

Write a PHP program that prints numbers from 10 down to 1 using a for loop.

PHP Solution

<?php
for ($i = 10; $i >= 1; $i--) {
    echo $i . "\n";
}
?>

Sample Output

10
9
8
7
6
5
4
3
2
1

Explanation

The loop starts at 10 and continues while $i >= 1.

The decrement operator ($i--) reduces the value by 1 after every iteration. When $i becomes 0, the condition is false, and the loop ends.

Reverse loops are useful for countdowns, descending lists, and processing items in reverse order.

Concepts Covered

  • for loop
  • Decrement operator
  • Reverse counting
  • Loop condition
  • Descending sequences

Question 7: Count Employees with Salaries Above ₹30,000

Problem Statement

A company stores employee salaries in an array. Write a PHP program that counts how many employees earn more than ₹30,000 using a for loop.

PHP Solution

<?php
$salaries = [25000, 35000, 42000, 28000, 50000, 30000];

$count = 0;
$totalEmployees = count($salaries);

for ($i = 0; $i < $totalEmployees; $i++) {
    if ($salaries[$i] > 30000) {
        $count++;
    }
}

echo "Employees earning above ₹30000: " . $count;
?>

Sample Output

Employees earning above ₹30000: 3

Explanation

The count() function returns the number of elements in the salary array. Here, there are six salaries, so the loop processes indexes 0 through 5.

Inside the loop, the if statement checks whether each salary is greater than ₹30,000. If the condition is true, $count++ increases the employee count by 1.

The salaries ₹35,000, ₹42,000, and ₹50,000 meet the condition, so the final count is 3.

Concepts Covered

  • for loop
  • Indexed arrays
  • count() function
  • Array indexing
  • if statement
  • Counter variable

Question 8: Calculate the Average Marks of Students

Problem Statement

A teacher stores the marks of five students in an array. Write a PHP program that calculates the total marks and average marks using a for loop.

PHP Solution

<?php
$marks = [80, 75, 90, 85, 70];

$total = 0;
$totalStudents = count($marks);

for ($i = 0; $i < $totalStudents; $i++) {
    $total += $marks[$i];
}

$average = $total / $totalStudents;

echo "Total Marks: " . $total . "\n";
echo "Average Marks: " . $average;
?>

Sample Output

Total Marks: 400
Average Marks: 80

Explanation

The program stores five students’ marks in an indexed array.

The for loop visits each element and adds its value to $total. After the loop finishes, the program divides the total marks by the number of students to calculate the average.

The total is 400, and there are five students. Therefore:

Average = 400 / 5 = 80

Concepts Covered

  • for loop
  • Indexed arrays
  • Total calculation
  • Average calculation
  • count() function
  • Arithmetic operations

Question 9: Print a Right-Angled Star Pattern

Problem Statement

Write a PHP program that prints a right-angled triangle pattern containing five rows of stars using a for loop.

PHP Solution

<?php
for ($i = 1; $i <= 5; $i++) {
    for ($j = 1; $j <= $i; $j++) {
        echo "* ";
    }

    echo "\n";
}
?>

Sample Output

*
* *
* * *
* * * *
* * * * *

Explanation

This program uses two nested for loops.

The outer loop controls the number of rows, from 1 to 5. The inner loop prints stars according to the current row number.

For example:

  • Row 1 prints one star.
  • Row 2 prints two stars.
  • Row 3 prints three stars.
  • Row 5 prints five stars.

After each row, echo "\n"; moves the output to the next line.

Concepts Covered

  • Nested for loops
  • Pattern printing
  • Inner and outer loops
  • Repeated characters
  • Newline output

Question 10: Calculate Monthly Sales and Identify the Highest Month

Problem Statement

A company records its sales for six months. Write a PHP program that calculates total sales and identifies the month with the highest sales using a for loop.

PHP Solution

<?php
$months = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June"
];

$sales = [45000, 52000, 48000, 65000, 70000, 62000];

$totalSales = 0;
$highestSales = $sales[0];
$highestMonth = $months[0];

$totalMonths = count($sales);

for ($i = 0; $i < $totalMonths; $i++) {
    $totalSales += $sales[$i];

    if ($sales[$i] > $highestSales) {
        $highestSales = $sales[$i];
        $highestMonth = $months[$i];
    }
}

echo "Total Sales: ₹" . $totalSales . "\n";
echo "Highest Sales Month: " . $highestMonth . "\n";
echo "Highest Sales Amount: ₹" . $highestSales;
?>

Sample Output

Total Sales: ₹342000
Highest Sales Month: May
Highest Sales Amount: ₹70000

Explanation

The program stores month names and their corresponding sales values in two arrays. Matching indexes connect each month with its sales amount.

The loop adds each month’s sales to $totalSales. It also compares the current month’s sales with $highestSales.

Whenever a higher sales value is found, the program updates both $highestSales and $highestMonth.

May has the highest sales of ₹70,000, and the total sales for all six months are ₹3,42,000.

Concepts Covered

  • for loop
  • Indexed arrays
  • Multiple arrays
  • Total calculations
  • Finding the maximum value
  • Conditional comparisons
  • Business data analysis

Key Takeaways

  • A for loop repeats a block of code while its condition remains true.
  • Its three main parts are initialization, condition, and increment or decrement.
  • The ++ operator increases a counter by one, while -- decreases it by one.
  • The += operator can increase a counter by more than one or add values to a running total.
  • Use accumulator variables to calculate totals, factorials, and averages.
  • Use count() to find the number of elements in an array.
  • A for loop can process indexed arrays using their numeric indexes.
  • Nested for loops are useful for patterns and other repeated operations.
  • Always check the loop condition carefully to avoid infinite loops and off-by-one errors.
  • PHP for loops are useful for calculations, reports, counting, and processing structured data.

Frequently Asked Questions (FAQs)

1. What is a for loop in PHP?

A for loop repeatedly executes a block of code while a specified condition remains true. It is especially useful when you know how many times an operation should repeat.

2. What are the three parts of a PHP for loop?

A typical for loop has three parts: initialization, condition, and increment or decrement. Initialization sets the starting value, the condition determines whether the loop continues, and the final expression updates the counter after each iteration.

3. What is the syntax of a for loop in PHP?

The basic syntax is:

for (initialization; condition; increment_or_decrement) {
    // Code to execute
}

4. What is the difference between i++ and i–?

$i++ increases the value of $i by one, while $i-- decreases it by one. They are commonly used to control the direction of a loop.

5. Can we use a for loop with an array in PHP?

Yes. You can use a for loop to access array elements by their numeric indexes. The count() function can help determine how many elements need to be processed when the array has consecutive numeric indexes starting at zero.

6. What is a nested for loop in PHP?

A nested for loop is a for loop placed inside another for loop. It is commonly used to create patterns, process rows and columns, and work with two-dimensional data.

7. How can we calculate the sum of numbers using a for loop?

Create a variable initialized to zero, then add each number to it inside the loop. For example, $sum += $i; adds the current value of $i to the running total.

8. Can a for loop run without an increment statement?

Yes. The increment expression is optional, but you must ensure the loop variable changes somewhere if the condition depends on it. Otherwise, the loop may run indefinitely.

9. What happens if the condition of a for loop is initially false?

The loop body does not execute. PHP checks the condition before the first iteration.

10. When should I use a for loop instead of foreach in PHP?

Use a for loop when you need a numeric counter, control over increments, or index-based processing. Use foreach when you want to iterate directly over array elements without manually managing indexes.

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top