Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

References left by foreach

A foreach by-reference binding and lingering reference let the loop variable alias each array element in turn, and then the last visited element after a nonempty loop.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

foreach ($values as &$value) { /* mutate */ } unset($value);

A foreach by-reference binding and lingering reference let the loop variable alias each array element in turn, and then the last visited element after a nonempty loop. A second by-value loop that reuses that variable may overwrite the final slot. Unset the loop variable to detach it without deleting the element. An empty loop creates no new binding.

function run(bool $detach): array {
    $a = [1, 2, 3];
    foreach ($a as &$v) { $v *= 2; }
    if ($detach) { unset($v); }
    foreach ($a as $v) {}
    return $a;
}
echo json_encode([run(false), run(true)]);
[[2,4,4],[2,4,6]]

Examples

<?php
function run(bool $detach): array {
    $a = [1, 2, 3];
    foreach ($a as &$v) { $v *= 2; }
    if ($detach) { unset($v); }
    foreach ($a as $v) {}
    return $a;
}
echo json_encode([run(false), run(true)]);

Result

[[2,4,4],[2,4,6]]

Sources