PHP Foreach and Nested Loops Practice Questions with Solutions

PHP provides different types of loops to process data efficiently. The foreach loop is especially useful for working with arrays, while nested loops allow one loop to run inside another. These concepts are commonly used to process student marks, employee records, sales data, tables, and patterns. In this chapter, you will practise both foreach and nested loops through solved PHP questions with working code, sample outputs, and easy-to-understand explanations. PHP Foreach and Nested Loops Practice Questions with Solutions to help you understand the concepts.

Question 1: Display All Elements of an Array Using Foreach

Problem Statement:
Create a PHP program that stores five programming languages in an array and displays each language using a foreach loop.

PHP Solution

<?php
$languages = ["PHP", "Python", "Java", "C++", "JavaScript"];

foreach ($languages as $language) {
    echo $language . "<br>";
}
?>

Sample Output

PHP
Python
Java
C++
JavaScript

Explanation

The $languages array stores five programming languages.

The foreach loop takes each element from the array and temporarily stores it in the $language variable. The echo statement displays the current language.

The loop automatically processes every element, so you do not need to manage an array index or increment a counter manually.

Concepts Covered

  • foreach loop
  • Indexed arrays
  • Array elements
  • Displaying data

Question 2: Calculate the Total of Employee Salaries

Problem Statement:
A company stores the monthly salaries of five employees in an array. Write a PHP program to calculate the total salary using a foreach loop.

EmployeeMonthly Salary
Amit25000
Neha30000
Rahul35000
Priya40000
Karan28000

PHP Solution

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

$totalSalary = 0;

foreach ($salaries as $salary) {
    $totalSalary += $salary;
}

echo "Total Monthly Salary = " . $totalSalary;
?>

Sample Output

Total Monthly Salary = 158000

Explanation

The $totalSalary variable starts at 0. During each iteration, the current salary is added to the total.

The foreach loop processes all five salary values. After the loop finishes, the program displays the combined monthly salary.

This technique is useful for calculating payroll totals, expenses, sales, and other business figures.

Concepts Covered

  • foreach loop
  • Numeric arrays
  • Running total
  • Addition operator
  • Employee salary calculations

Question 3: Display Employees Earning More Than ₹30,000

Problem Statement:
A company maintains a list of employee salaries. Write a PHP program to display only the salaries greater than ₹30,000 using a foreach loop and an if condition.

PHP Solution

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

foreach ($salaries as $salary) {
    if ($salary > 30000) {
        echo $salary . "<br>";
    }
}
?>

Sample Output

35000
42000
50000

Explanation

The foreach loop checks every salary in the array. The if statement determines whether the current salary is greater than 30000.

Only salaries that satisfy the condition are displayed. A salary of exactly 30000 is excluded because the program uses the > operator.

Concepts Covered

  • foreach loop
  • if condition
  • Comparison operators
  • Filtering array values
  • Business data processing

Question 4: Display Employee Names and Salaries Using an Associative Array

Problem Statement:
Create an associative array containing employee names and salaries. Use a foreach loop to display each employee’s name alongside their salary.

PHP Solution

<?php
$employees = [
    "Amit" => 25000,
    "Neha" => 30000,
    "Rahul" => 35000,
    "Priya" => 40000
];

foreach ($employees as $name => $salary) {
    echo $name . " earns Rs. " . $salary . "<br>";
}
?>

Sample Output

Amit earns Rs. 25000
Neha earns Rs. 30000
Rahul earns Rs. 35000
Priya earns Rs. 40000

Explanation

An associative array stores information using key-value pairs. In this example, employee names are the keys and salaries are the values.

The statement foreach ($employees as $name => $salary) assigns the current key to $name and its corresponding value to $salary.

This approach is useful when each value is associated with a meaningful label, such as an employee name, product name, or department.

Concepts Covered

  • Associative arrays
  • foreach with keys and values
  • Key-value pairs
  • Employee records
  • String concatenation

Question 5: Calculate the Average Marks of Students

Problem Statement:
A teacher stores the marks of five students in an associative array. Write a PHP program to display each student’s marks and calculate the class average.

PHP Solution

<?php
$students = [
    "Aman" => 80,
    "Riya" => 75,
    "Karan" => 90,
    "Simran" => 85,
    "Rahul" => 70
];

$totalMarks = 0;
$totalStudents = 0;

foreach ($students as $name => $marks) {
    echo $name . ": " . $marks . "<br>";

    $totalMarks += $marks;
    $totalStudents++;
}

$average = $totalMarks / $totalStudents;

echo "Total Marks = " . $totalMarks . "<br>";
echo "Class Average = " . $average;
?>

Sample Output

Aman: 80
Riya: 75
Karan: 90
Simran: 85
Rahul: 70
Total Marks = 400
Class Average = 80

Explanation

The associative array stores each student’s name and marks.

The foreach loop displays each student’s result, adds the marks to $totalMarks, and increases $totalStudents by one.

After the loop, the program divides the total marks by the number of students to calculate the average.

For an empty array, the program would need an additional check before performing the division.

Concepts Covered

  • Associative arrays
  • foreach loop
  • Accumulator variables
  • Counting records
  • Average calculation

Question 6: Print a Rectangle Pattern Using Nested Loops

Problem Statement:
Write a PHP program to print a rectangle containing four rows and five stars in each row using nested for loops.

PHP Solution

<?php
for ($row = 1; $row <= 4; $row++) {
    for ($col = 1; $col <= 5; $col++) {
        echo "* ";
    }

    echo "<br>";
}
?>

Sample Output

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

Explanation

A nested loop is a loop placed inside another loop.

  • The outer loop controls the four rows.
  • The inner loop prints five stars in each row.
  • After the inner loop finishes, <br> moves the output to the next line in a browser.

The inner loop completes all five iterations for every single iteration of the outer loop.

Concepts Covered

  • Nested for loops
  • Outer and inner loops
  • Row and column counters
  • Pattern printing
  • Repeated execution

Question 7: Print a Right-Angled Triangle Using Nested Loops

Problem Statement:
Write a PHP program to print a right-angled triangle containing five rows of stars.

PHP Solution

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

    echo "<br>";
}
?>

Sample Output

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

Explanation

The outer loop controls the number of rows. The inner loop runs from 1 up to the current row number.

For example, the first row prints one star, the second row prints two stars, and the fifth row prints five stars.

The condition $col <= $row makes the number of stars increase with each row.

Concepts Covered

  • Nested loops
  • Pattern printing
  • Row-dependent conditions
  • Loop counters
  • Increment operators

Question 8: Display Multiplication Tables from 1 to 5

Problem Statement:
Write a PHP program using nested loops to display multiplication tables from 1 to 5, with each table showing multiplications from 1 to 5.

PHP Solution

<?php
for ($num = 1; $num <= 5; $num++) {
    echo "Table of " . $num . "<br>";

    for ($i = 1; $i <= 5; $i++) {
        echo $num . " x " . $i . " = " . ($num * $i) . "<br>";
    }

    echo "<br>";
}
?>

Sample Output

Table of 1
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5

Table of 2
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

Table of 3
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15

Table of 4
4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20

Table of 5
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25

Explanation

The outer loop selects the number whose multiplication table is being generated. The inner loop multiplies that number by each value from 1 to 5.

For every outer-loop iteration, the inner loop runs five times. Once a table is complete, an extra <br> creates a blank line before the next table.

Concepts Covered

  • Nested for loops
  • Multiplication
  • Generating tables
  • Loop counters
  • Formatting browser output

Question 9: Display Marks Stored in a Two-Dimensional Array

Problem Statement:
A school stores marks for three students across three subjects. Write a PHP program using nested foreach loops to display each student’s marks.

PHP Solution

<?php
$students = [
    "Aman" => [
        "Maths" => 85,
        "Science" => 90,
        "English" => 80
    ],
    "Riya" => [
        "Maths" => 92,
        "Science" => 88,
        "English" => 95
    ],
    "Karan" => [
        "Maths" => 78,
        "Science" => 82,
        "English" => 75
    ]
];

foreach ($students as $name => $subjects) {
    echo "Student: " . $name . "<br>";

    foreach ($subjects as $subject => $marks) {
        echo $subject . ": " . $marks . "<br>";
    }

    echo "<br>";
}
?>

Sample Output

Student: Aman
Maths: 85
Science: 90
English: 80

Student: Riya
Maths: 92
Science: 88
English: 95

Student: Karan
Maths: 78
Science: 82
English: 75

Explanation

The $students array is a multidimensional associative array. Each student has another array containing subject names and marks.

The outer foreach loop selects a student and their subject array. The inner foreach loop processes each subject and its marks.

This structure is useful for handling grouped information, such as students and subjects, departments and employees, or products and their details.

Concepts Covered

  • Multidimensional arrays
  • Nested foreach loops
  • Associative arrays
  • Grouped data
  • Student result processing

Question 10: Calculate Department-Wise Sales Using Nested Foreach Loops

Problem Statement:
A company stores sales figures for different departments across multiple months. Write a PHP program to display the sales for each department and calculate the total sales for each department.

Sales Data

DepartmentJanuaryFebruaryMarch
Electronics500006000055000
Clothing300003500040000
Furniture450005000048000

PHP Solution

<?php
$sales = [
    "Electronics" => [
        "January" => 50000,
        "February" => 60000,
        "March" => 55000
    ],
    "Clothing" => [
        "January" => 30000,
        "February" => 35000,
        "March" => 40000
    ],
    "Furniture" => [
        "January" => 45000,
        "February" => 50000,
        "March" => 48000
    ]
];

foreach ($sales as $department => $monthlySales) {
    $total = 0;

    echo "Department: " . $department . "<br>";

    foreach ($monthlySales as $month => $amount) {
        echo $month . ": Rs. " . $amount . "<br>";
        $total += $amount;
    }

    echo "Total Sales: Rs. " . $total . "<br><br>";
}
?>

Sample Output

Department: Electronics
January: Rs. 50000
February: Rs. 60000
March: Rs. 55000
Total Sales: Rs. 165000

Department: Clothing
January: Rs. 30000
February: Rs. 35000
March: Rs. 40000
Total Sales: Rs. 105000

Department: Furniture
January: Rs. 45000
February: Rs. 50000
March: Rs. 48000
Total Sales: Rs. 143000

Explanation

The outer foreach loop selects each department and its monthly sales data. The inner loop processes the sales figures for January, February, and March.

The $total variable is reset to 0 at the beginning of each department’s calculation. Each monthly amount is added to that department’s total.

The program displays the monthly figures and the final total for every department.

This approach is useful for preparing department-wise reports, monthly sales summaries, and business performance reports.

Concepts Covered

  • Nested foreach loops
  • Multidimensional associative arrays
  • Department-wise calculations
  • Running totals
  • Business reporting

Key Takeaways

  • A foreach loop is designed to process arrays without manually managing an index.
  • Use foreach ($array as $value) when you need only the array values.
  • Use foreach ($array as $key => $value) when you need both keys and values.
  • Associative arrays store information as key-value pairs.
  • Nested loops allow one loop to execute inside another loop.
  • The outer loop commonly controls rows or groups, while the inner loop processes their individual elements.
  • Multidimensional arrays can store related information in groups, such as students and subjects or departments and sales.
  • A total variable should be initialized before accumulating values.
  • When calculating separate totals, reset the accumulator for each group.
  • Always use clear loop-variable names to make nested loops easier to understand.

Frequently Asked Questions (FAQs)

1. What is a foreach loop in PHP?

A foreach loop is used to process each element of an array. It automatically retrieves array elements, so you generally do not need to manage indexes manually.

2. What is the syntax of a foreach loop?

The basic syntax is:

foreach ($array as $value) {
    // Code to execute
}

PHP assigns each array element to $value during each iteration.

3. How can I access both the key and value in a foreach loop?

Use the following syntax:

foreach ($array as $key => $value) {
    echo $key . ": " . $value . "<br>";
}

This is especially useful for associative arrays.

4. What is a nested loop in PHP?

A nested loop is a loop placed inside another loop. The inner loop executes its iterations for each iteration of the outer loop, provided the outer loop continues.

5. Can I use a foreach loop inside another foreach loop?

Yes. Nested foreach loops are useful for processing multidimensional arrays, such as student marks grouped by subject or sales grouped by department.

6. What is the difference between foreach and for loops?

A foreach loop is convenient for processing array elements directly. A for loop is useful when you need more control over initialization, conditions, and counter updates.

7. How many times does a nested loop execute?

The total number of inner-loop executions depends on both loops. If an outer loop runs three times and an inner loop runs four times during every outer iteration, the inner loop executes 12 times in total.

8. Can I use if statements inside foreach loops?

Yes. An if statement inside a foreach loop lets you filter or process elements according to a condition, such as displaying salaries above ₹30,000.

9. What is a multidimensional array in PHP?

A multidimensional array contains one or more arrays inside another array. It can represent structured information, such as students with subject marks or departments with monthly sales.

10. When should I use nested loops?

Use nested loops when you need to process grouped or tabular data, generate patterns, create multiplication tables, or work with multidimensional arrays.

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

Scroll to Top