CodeBlanks Logo Icon CodeBlanks

The foreach loop

PHP course · Beginner · Lesson 45/116

Learn to walk through all elements of an array with foreach.

The foreach loop

The foreach loop is used to walk through every element of an array. First you define an array, then with foreach ($array as $item) you take each element in turn.

For example, $fruits = ["apple", "banana", "cherry"]; creates an array of three fruits. With foreach ($fruits as $fruit), on each step $fruit becomes "apple", then "banana", then "cherry".

The element variable

In a foreach loop, the variable after the as keyword holds the current element. You can name it anything you like; a singular name is usually clearest.

For example, with $prices = [10, 20, 30]; and foreach ($prices as $price), the variable $price becomes 10, then 20, then 30. You can work with $price on each step.

Exercise Print the fruits

Walk through the $fruits array with foreach and print each fruit on its own line with echo.

Show example solution
Write foreach ($fruits as $fruit) and print with echo $fruit . "\n".
Example solution:
<?php
$fruits = ["apple", "banana", "cherry"];
// Print each fruit on its own line
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}

Test yourself

  1. What is the output of the code below?

    $fruits = ['a', 'b'];
    foreach ($fruits as $f) {
        echo $f;
    }
    • a
    • ab
    • ba
    • ab
    Show answer

    ab — Correct. foreach walks each element in order: a then b.

  2. Complete the foreach pattern

    $fruits = ["apple", "banana"];
    foreach ($fruits ____ $fruit) {
        echo $fruit;
    }
    Show answer
    $fruits = ["apple", "banana"];
    foreach ($fruits as $fruit) {
        echo $fruit;
    }
  3. Match the foreach parts

    foreach
    Walks array elements
    as
    Assigns each element to a variable
    $fruit
    Holds a single element
  4. What does the 'as' keyword do in a foreach loop?

    • It ends the loop
    • It checks the condition
    • It increases a counter
    • It assigns each element to a variable
    Show answer

    It assigns each element to a variable — Correct. as assigns each element to the given variable.

All lessons in Beginner