Open In App

How to Loop Through an Array using a foreach Loop in PHP?

Given an array (indexed or associative), the task is to loop through the array using foreach loop. The foreach loop iterates through each array element and performs the operations.

PHP foreach Loop

The foreach loop iterates over each key/value pair in an array. This loop is mainly useful for iterating through associative arrays where you need both the key and the value. The foreach loop iterates over an array of elements, the execution is simplified and finishes the loop in less time comparatively. The foreach loop works for both indexed and associative arrays.

Example 1: In this example, we will use foreach loop to iterate over an indexed array.

<?php

// Indexed array
$arr = array(10, 20, 30, 40, 50);

foreach ($arr as $element) {
    echo $element . " ";
}

?>

Output
10 20 30 40 50 

Example 2: In this example, we will use foreach loop to iterate over an associative array.

<?php

// Associative array
$student_marks = array(
    "Maths" => 95, 
    "Physics" => 90,   
    "Chemistry" => 96, 
    "English" => 93,   
    "Computer" => 98
);

foreach ($student_marks as $key => $value) {
    echo "$key => $value\n";
}

?>

Output
Maths => 95
Physics => 90
Chemistry => 96
English => 93
Computer => 98
Article Tags :