note 129172 added to control-structures.foreach

From: Date: Thu, 18 Jan 2024 14:34:37 +0000
Subject: note 129172 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-221126@lists.php.net to get a copy of this message
Note that when you use foreach on an array of objects, the objects appear to be copies of references. So, you can modify the object, but not replace it entirely like you can when passing by reference. <?php > $x = array_map(function ($n) { $tmp = new stdClass; $tmp->a = $n; return $tmp; }, [1,2,3]) = [ {#6010 +"a": 1, }, {#6060 +"a": 2, }, {#6062 +"a": 3, }, ] > foreach ($x as $y) { if ($y->a === 2) { $y->a = 7; } } > $x = [ {#6010 +"a": 1, }, {#6060 +"a": 7, }, {#6062 +"a": 3, }, ] > foreach ($x as $y) { if ($y->a === 2) { $y = 7; } } > $x = [ {#6010 +"a": 1, }, {#6060 +"a": 7, }, {#6062 +"a": 3, }, ] ?> This is PHP 8.2. These code snippets were run in Laravel's Tinker. ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.134 (proxied: 2605:59c8:20c4:a510:d927:b3d8:2748:54f9) ---- Manual Page -- https://php.net/manual/en/control-structures.foreach.php Edit -- https://main.php.net/note/edit/129172 Del: integrated -- https://main.php.net/note/delete/129172/integrated Del: useless -- https://main.php.net/note/delete/129172/useless Del: bad code -- https://main.php.net/note/delete/129172/bad+code Del: spam -- https://main.php.net/note/delete/129172/spam Del: non-english -- https://main.php.net/note/delete/129172/non-english Del: in docs -- https://main.php.net/note/delete/129172/in+docs Del: other reasons-- https://main.php.net/note/delete/129172 Reject -- https://main.php.net/note/reject/129172 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#221126) next »