CKTIS / PHP
Loops and iteration
A foreach loop visits array entries in their current iteration order and can bind both key and value. continue starts the next iteration, while break exits the loop.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
foreach ($rows as $key => $value) { /* body */ }A foreach loop visits array entries in their current iteration order and can bind both key and value. continue starts the next iteration, while break exits the loop. An empty array produces no iterations. Rebinding a by-value loop variable does not replace a scalar array element. A prior by-reference foreach leaves the last element bound. Use unset($v) before reusing the variable by value or the last element can be overwritten.
$rows=["a"=>0,"b"=>2,"c"=>-1,"d"=>5]; $seen=[]; foreach($rows as $key=>$v){if($v===0)continue; if($v<0)break; $seen[]=$key; $v=99;}
echo json_encode([$seen,$rows["b"]]);
function again($clear){$a=[1,2,3];foreach($a as &$v){}if($clear)unset($v);foreach($a as $v){}return $a;}echo "\n",json_encode([again(false),again(true)]);
[["b"],2]
[[1,2,2],[1,2,3]]
Examples
<?php
$rows=["a"=>0,"b"=>2,"c"=>-1,"d"=>5]; $seen=[]; foreach($rows as $key=>$v){if($v===0)continue; if($v<0)break; $seen[]=$key; $v=99;}
echo json_encode([$seen,$rows["b"]]);
function again($clear){$a=[1,2,3];foreach($a as &$v){}if($clear)unset($v);foreach($a as $v){}return $a;}echo "\n",json_encode([again(false),again(true)]);
Result
[["b"],2] [[1,2,2],[1,2,3]]