Lesson 17 of 50 – PHP Foreach Loop
34%

PHP Foreach Loop

The foreach loop is used to access each element of an array. It is especially useful when we do not know the number of elements in an array.

1. What Is a Foreach Loop?

A foreach loop automatically reads each element of an array one by one.

<?php
$colors = ["Red", "Green", "Blue"];

foreach ($colors as $color) {
    echo $color . "<br>";
}
?>
Output:
Red
Green
Blue

Here, $color receives each array value during every iteration.

2. Foreach with an Indexed Array

An indexed array stores values using numeric indexes. Foreach reads the values in their iteration order.

<?php
$fruits = ["Apple", "Mango", "Banana", "Orange"];

foreach ($fruits as $fruit) {
    echo $fruit . "<br>";
}
?>
Output:
Apple
Mango
Banana
Orange

We do not need to manage an index variable manually.

3. Foreach with an Associative Array

An associative array stores data using named keys. We can access both keys and values with foreach.

<?php
$student = [
    "name" => "Rahul",
    "age" => 20,
    "course" => "PHP"
];

foreach ($student as $key => $value) {
    echo $key . ": " . $value . "<br>";
}
?>
Output:
name: Rahul
age: 20
course: PHP

The variable $key stores the current key, while $value stores its corresponding value.

4. Foreach Using Keys and Values

The general syntax for accessing keys and values is:

foreach ($array as $key => $value) {
    // Statements
}

Example:

<?php
$marks = [
    "English" => 85,
    "Math" => 90,
    "Computer" => 95
];

foreach ($marks as $subject => $mark) {
    echo $subject . " = " . $mark . "<br>";
}
?>
Output:
English = 85
Math = 90
Computer = 95

This approach is useful for displaying student marks, product prices, employee details, and other records.

5. Foreach with Numeric Indexes

We can also retrieve the numeric index and value of an indexed array.

<?php
$subjects = ["English", "Hindi", "Math", "Science"];

foreach ($subjects as $index => $subject) {
    echo "Index " . $index . ": " . $subject . "<br>";
}
?>
Output:
Index 0: English
Index 1: Hindi
Index 2: Math
Index 3: Science

Remember that array indexes do not always start at zero. If an array has custom numeric keys, foreach uses those actual keys.

6. Modifying Array Values Using Foreach

By default, the loop variable receives a copy of each array value. Changing that variable does not update the original array.

<?php
$numbers = [10, 20, 30];

foreach ($numbers as $number) {
    $number = $number + 5;
}

print_r($numbers);
?>
Output:
Array
(
    [0] => 10
    [1] => 20
    [2] => 30
)

To update the original array values, use a reference with &.

<?php
$numbers = [10, 20, 30];

foreach ($numbers as &$number) {
    $number = $number + 5;
}

unset($number);

print_r($numbers);
?>
Output:
Array
(
    [0] => 15
    [1] => 25
    [2] => 35
)

Important: Always use unset($number) after a reference-based foreach loop to remove the reference. Otherwise, the variable can remain linked to the last array element.

7. Nested Foreach Loop

A foreach loop inside another foreach loop is called a nested foreach loop. It is useful for multidimensional arrays.

<?php
$students = [
    ["name" => "Rahul", "marks" => 85],
    ["name" => "Amit", "marks" => 90],
    ["name" => "Priya", "marks" => 95]
];

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

    echo "<hr>";
}
?>
Output:
name: Rahul
marks: 85

name: Amit
marks: 90

name: Priya
marks: 95

The outer loop accesses each student, and the inner loop accesses the details of that student.

8. Difference Between For and Foreach
For Loop Foreach Loop
Uses initialization, condition, and update. Iterates over array elements.
Often used when the iteration count is known. Useful for processing array values.
Can be used with numeric counters. Can access values and keys directly.
Index management may be required. No manual counter is needed for normal array iteration.

For loop example:

<?php
$numbers = [10, 20, 30];

for ($i = 0; $i < count($numbers); $i++) {
    echo $numbers[$i] . "<br>";
}
?>

Foreach example:

<?php
$numbers = [10, 20, 30];

foreach ($numbers as $number) {
    echo $number . "<br>";
}
?>
9. Practical Example: Display Product Prices

Suppose we want to display a list of products and their prices. An associative array and foreach loop make this task simple.

<?php
$products = [
    "Keyboard" => 500,
    "Mouse" => 300,
    "Monitor" => 7000,
    "Printer" => 5500
];

echo "<h3>Product List</h3>";

foreach ($products as $product => $price) {
    echo $product . " - Rs. " . $price . "<br>";
}
?>
Output:
Product List
Keyboard - Rs. 500
Mouse - Rs. 300
Monitor - Rs. 7000
Printer - Rs. 5500
Practice Assignment
  1. Create an array containing five city names and display them using foreach.
  2. Create an associative array of five students and their marks.
  3. Display each subject and its marks using keys and values.
  4. Create a product array and display all product names and prices.
  5. Create a multidimensional array of three students and display their names and marks.

🧠 Quick Quiz

1. What is the main purpose of a foreach loop?




2. Which syntax accesses both the key and value?




3. What should you do after using a reference variable in foreach?