How to Use foreach Loop in PHP

The foreach loop in PHP is used to iterate over arrays and objects easily. It allows you to access each element’s value, and optionally its key, without using a counter. This makes it ideal for working with both indexed and associative arrays. The syntax is simple and improves code readability. It is one of the most commonly used loops in PHP for handling data collections.

Basic Syntax:


foreach ($array as $value) {
    // Code to run for each value
}

Example 1: Loop through indexed array

File name: colors.php


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

foreach ($colors as $color) {
    echo $color . "
";
}
?>

Output:


Red
Green
Blue

Example 2: Loop through associative array

File name: index.php


<?php
$user = [
    'name' => 'John',
    'age' => 25,
    'email' => 'john@example.com'
];

foreach ($user as $key => $value) {
    echo "$key: $value
";
}
?>

Output:


name: John  
age: 25  
email: john@example.com

Summary

Use Case Syntax Example
Loop values only foreach ($arr as $value)
Loop keys + values foreach ($arr as $key => $value)