php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #8373 foreach by reference
Submitted: 2000-12-22 05:47 UTC Modified: 2001-01-23 12:09 UTC
From: ocomte at guarantycity dot com Assigned:
Status: Duplicate Package: Feature/Change Request
PHP Version: 4.0.4 OS: All
Private report: No CVE-ID: None
 [2000-12-22 05:47 UTC] ocomte at guarantycity dot com
It would be very useful (at least for me) if the fonction foreach support references. For example the code :
<?
class Foo
{	var $Ok=false;
	function EchoOk()
	{	if ($this->Ok)
			echo "OK<br>\n";
		else
			echo "KO<br>\n";
	}
}

$Bar=array();
$Bar[]=new Foo;
foreach($Bar as $v)
	$v->SetOk();
foreach($Bar as $v)
	$v->EchoOk();
?>
will produce the output :
KO<br>

I know I can replace the first loop by :
foreach($Bar as $k => $v)
	$Bar[$k]->SetOk();
but, in this case, the $v is useless.

I suggest to accept the notation
foreach($Arr as &$RefVal)
and
foreach($Arr as $Key => &$RefVal)
in a future PHP release to make $RefVal a reference on each $Arr elements (and not a copy).

Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2001-01-23 12:09 UTC] cynic@php.net
dupe of #3074

btw, +1 for foreach( $a as &$v ) :)
 [2003-11-10 06:28 UTC] giles_m_allen at yahoo dot co dot uk
I Agree, it would be usefull, it there any way in which you can force it to pass by reference as it is?
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Dec 11 20:01:26 2024 UTC