php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #15663 add foreach reference values
Submitted: 2002-02-21 12:34 UTC Modified: 2004-01-10 10:36 UTC
Votes:6
Avg. Score:5.0 ± 0.0
Reproduced:5 of 5 (100.0%)
Same Version:1 (20.0%)
Same OS:1 (20.0%)
From: greg at mtechsolutions dot ca Assigned:
Status: Closed Package: Feature/Change Request
PHP Version: 4.1.1 OS:
Private report: No CVE-ID: None
 [2002-02-21 12:34 UTC] greg at mtechsolutions dot ca
Just a small request that could be fairly useful.

Say you have an array of objects, $objects. Right now, doing:

foreach ($objects as $obj) {
   $obj->something();
}

will create a copy of each object (using unnecessary memory) and call something() on the copy, not the actual object (which is bad if it's a mutator function of that class).

The best way to do it now is to do:

foreach (array_keys($objects) as $key) {
   $objects[$key]->something();
}

but it would be very cool if php had the syntax:

foreach ($objects as &$obj)

where it would create $obj as a reference to each object.

thanks

Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2002-02-21 17:20 UTC] mfischer@php.net
Objects are bad examples as they will completely change how they behave in ZE2. However, it is true for normal arrays and it's in the TODO list of PHP:

"Zend
----
    * allow foreach ($array as $k => &$val) syntax. right now we cannot 
      traverse an array without copying each element."
 [2002-02-21 20:21 UTC] yohgaki@php.net
This bug has been fixed in CVS.

ZendEngine2 uses handle for object.
 [2002-02-21 20:37 UTC] mfischer@php.net
Don't close, it does apply to arrays.
 [2002-04-07 16:59 UTC] vdhome at idas dot cz
Can I expect this anytime soon, please?
And what is "ZendEngine2" - is it what will be in 4.2.0? I haven't found any information on what will be in 4.2.0. Is it anywhere on the website? Thanks.
 [2003-01-25 11:03 UTC] derick@php.net
Not likely that this will be addressed at all, atleast I won't do it.

Derick
 [2004-01-10 10:36 UTC] andrey@php.net
PHP5 has support for traversing arrays with objects and getting not a copy but a reference :
foreach ($a as &$v) {

}
Example code :
<?php
$a = array((object)1, (object)2,(object)3,(object)4);
var_dump($a);
foreach ($a as &$v) {
        $v->scalar++;

}
var_dump($a);
?>
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Sun Mar 03 11:01:29 2024 UTC