PHP · Course navigation

PHP Arrays

Loop through an indexed array.

On this page

The concept

An indexed array preserves order. foreach assigns each item to $score before executing the loop body.

Code example

PHP
<?php
$scores = [82, 91, 76];
foreach ($scores as $score) {
    echo "$score\n";
}
Output
82
91
76

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1<?php
2$scores = [82, 91, 76];
3foreach ($scores as $score) {
4 echo "$score\n";
5}

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Create a three-element indexed array.$scores = [82, 91, 76]
—
foreach assigns each value to $score.$scores = [82, 91, 76]
—
Echo each score and a newline.$scores = [82, 91, 76]
82
91
76

Behind the scenes

How PHP processes this code

The PHP runtime executes the script. echo writes to the response or terminal output.