CKTIS / PHP
Keyword foreach
Traverse arrays and iterable objects using their keys and values.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
foreach ($items as $key => $value) { /* body */ }Traverse arrays and iterable objects using their keys and values. Ordinary iteration of an object can also expose properties visible in the current scope. Reassigning a fresh value variable does not modify the element. If the same variable is still bound to the last element after a reference loop, a subsequent by-value pass can turn [1,2,3] into [1,2,2]. Break the binding with unset.
$scores=["a"=>2,"b"=>4];
foreach($scores as $value){$value=0;}
foreach($scores as $key=>&$value){$value+=strlen($key);} unset($value);
echo json_encode($scores);
$raw=[1,2,3]; foreach($raw as &$slot){} foreach($raw as $slot){} unset($slot);
echo PHP_EOL,json_encode($raw);
{"a":3,"b":5}
[1,2,2]
Examples
<?php
$scores=["a"=>2,"b"=>4];
foreach($scores as $value){$value=0;}
foreach($scores as $key=>&$value){$value+=strlen($key);} unset($value);
echo json_encode($scores);
$raw=[1,2,3]; foreach($raw as &$slot){} foreach($raw as $slot){} unset($slot);
echo PHP_EOL,json_encode($raw);
Result
{"a":3,"b":5}
[1,2,2]