note 130531 added to control-structures.foreach

From: Date: Sat, 25 Oct 2025 16:36:28 +0000
Subject: note 130531 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-222399@lists.php.net to get a copy of this message
Definitely relevant for PHP 7+ 1. You can't change array during iteration Foreach WILL NOT LOOP through new values added to the array <?php while inside the loop. $a = [1, 2, 3]; foreach ($a as $k => $v) { echo $v; if ($v === 2) { $v[] = 4; } } ?> Output: 123 But the original array was modified: [1, 2, 3, 4] Foreach WILL LOOP through values deleted from the array while inside the loop. <?php $a = [1, 2, 3]; foreach ($a as $k => $v) { echo $v; if ($v === 2) { unset($a[2]); } } ?> Output: 123 But the original array was modified: [1, 2] 2. But If you iterate by reference using foreach ($arr as &$v) then $arr is turned into a reference and you can change it during iteration Foreach WILL LOOP through new values added to the array while inside the loop. <?php $a = [1, 2, 3]; foreach ($v as &$v) { echo $v; if ($v === 2) { $v[] = 4; } } ?> Output: 1234 Foreach WILL NOT LOOP through values deleted from the array while inside the loop. <?php $a = [1, 2, 3]; foreach ($a as $k => &$v) { echo $v; if ($v === 2) { unset($a[2]); } } ?> Output: 12 ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 2a03:d000:184:35c:31bd:5811:9420:ede6) ---- Manual Page -- https://php.net/manual/en/control-structures.foreach.php Edit -- https://main.php.net/note/edit/130531 Del: integrated -- https://main.php.net/note/delete/130531/integrated Del: useless -- https://main.php.net/note/delete/130531/useless Del: bad code -- https://main.php.net/note/delete/130531/bad+code Del: spam -- https://main.php.net/note/delete/130531/spam Del: non-english -- https://main.php.net/note/delete/130531/non-english Del: in docs -- https://main.php.net/note/delete/130531/in+docs Del: other reasons-- https://main.php.net/note/delete/130531 Reject -- https://main.php.net/note/reject/130531 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222399) next »