CodeBlanks Logo Icon CodeBlanks

Iterating an array

PHP course · Beginner · Lesson 57/116

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

Index loop with for

To walk through all elements of an array, you can use a for loop with indexes. The counter starts at 0 and goes up to count().

For example:
for ($i = 0; $i < count($scores); $i++) {
  echo $scores[$i];
}
prints each element in turn. $i acts as the index; $scores[$i] gives the value at that index.

Easy walking with foreach

The easiest way to walk an array is the foreach loop. It takes each element in turn without tracking the index.

The syntax is: foreach ($scores as $score) { ... }. Here $score takes one element of the array at each step. For [85, 92, 78] it is first 85, then 92, then 78. When you do not need the index, foreach is cleaner than for.

Exercise Print the scores with foreach

Walk the $scores = [85, 92, 78]; array with foreach and print each score on its own line with echo. Append "\n" to each line. Expected output: 85, 92, 78.

Show example solution
<?php
$scores = [85, 92, 78];
// Print the scores with foreach
foreach ($scores as $score) {
    echo $score . "\n";
}
Example solution:
<?php
$scores = [85, 92, 78];
// Print the scores with foreach
foreach ($scores as $score) {
    echo $score . "\n";
}

Test yourself

  1. What is the output of the code below?

    $scores = [10, 20, 30];
    for ($i = 0; $i < count($scores); $i++) {
        echo $scores[$i] . "\n";
    }
    • 0 1 2
    • 10 20 30
    • 10 20 30
    • 30 20 10
    Show answer

    10 20 30 — Correct. $i takes 0, 1 and 2; the elements are printed in order.

  2. Complete the foreach syntax

    $scores = [85, 92, 78];
    ____ $score) {
        echo $score . "\n";
    }
    Show answer
    $scores = [85, 92, 78];
    foreach ($scores as $score) {
        echo $score . "\n";
    }
  3. Match each loop or function to its feature

    for
    Walk by index
    foreach
    Walk by element
    count()
    Gives the limit
  4. When you only need the values of an array, which loop is cleaner?

    • for
    • while
    • foreach
    • do-while
    Show answer

    foreach — Correct. foreach gives each value without index tracking.

All lessons in Beginner