note 130666 added to control-structures.foreach

From: Date: Thu, 26 Feb 2026 14:01:32 +0000
Subject: note 130666 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-222560@lists.php.net to get a copy of this message
The following C code mimics the reference leak behavior of a by-reference foreach loop in PHP. By intentionally leaving current pointing to the last element after the first loop, we can reproduce the same silent array corruption that occurs in PHP. #include <stdio.h> int main() { int arr[] = {1, 2, 3, 4}; int *current; //First Loop doubles the array for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { //arr[i] === *(arr + i) arr[i] *= 2; current = arr + i; printf("Current modified:%d\n", *current); } /* After the loop completes, the arr is now {2,4,6,8}. As for current, it is going to have the memory location of the last element (memory location of 8). */ for (size_t i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { /* In each iteration, the memory location of 8 is going to be dereferenced and set to arr[i]. As a result, the last value will be equal to the value before it */ *current = arr[i]; printf("Current:%d\n", *current); } return 0; } Just as PHP's $value remains a reference to the last element after a by-reference foreach, current here remains a pointer to arr[3]. Every iteration of the second loop writes into arr[3], ultimately copying the second-to-last value onto the last element. ---- Server IP: 206.189.2.9 Probable Submitter: 83.171.206.236 ---- Manual Page -- https://php.net/manual/en/control-structures.foreach.php Edit -- https://main.php.net/note/edit/130666 Del: integrated -- https://main.php.net/note/delete/130666/integrated Del: useless -- https://main.php.net/note/delete/130666/useless Del: bad code -- https://main.php.net/note/delete/130666/bad+code Del: spam -- https://main.php.net/note/delete/130666/spam Del: non-english -- https://main.php.net/note/delete/130666/non-english Del: in docs -- https://main.php.net/note/delete/130666/in+docs Del: other reasons-- https://main.php.net/note/delete/130666 Reject -- https://main.php.net/note/reject/130666 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222560) next »