bhylu.com

Advertisements

PHP For and Foreach

A for loop makes a numeric progression explicit. foreach usually expresses traversal of an array more directly and works with keys as well as values.

How it works

Use an index when position is part of the requirement, not just because another language uses indexed loops. PHP arrays are ordered maps and may have string keys or gaps in integer keys, so a size-based numeric loop is not a universal way to traverse them. foreach can provide the key and value directly. Iterating by reference has a separate lifetime hazard; this first example deliberately uses ordinary value traversal.

Run it locally

Run this complete source locally with PHP 8.2 or newer. Save it using the filename shown and run the command below. PHP is not currently available in Bhylu’s browser playground. Apache and MySQL are not needed for an ordinary CLI example.

php -l for-foreach.php
php for-foreach.php

Download this source as a local PHP lab file. Keep lab files separate from the Bhylu project and production data.

Example

PHP 8.2+ · for-foreach.php

<?php
declare(strict_types=1);

for ($day = 1; $day <= 3; $day++) { echo "Day ", $day, "\n"; }
$stock = ["Spade" => 4, "Drill" => 2];
foreach ($stock as $item => $quantity) {
    echo $item, ": ", $quantity, "\n";
}

Expected result

Day 1
Day 2
Day 3
Spade: 4
Drill: 2

The first loop represents three explicit day numbers. The second follows the array’s entries without guessing their keys. It prints both the item identity and the count, which is more useful than displaying a series of unexplained numbers. Later collection operations can calculate a report while keeping the display loop simple.

Check the official PHP manual for detailed version and API contracts.