note 39966 added to language.references.whatdo

From: Date: Tue, 17 Feb 2004 08:39:58 +0000
Subject: note 39966 added to language.references.whatdo
Groups: php.notes 
Request: Send a blank email to php-notes+get-65260@lists.php.net to get a copy of this message
Say you want to search an array, with the intention of returning a reference to the value (so that the parent function can directly edit the array element). You cannot use "foreach" or "each" in the traditional way, because those functions will make a copies of the object, rather than return references to the original array element. <? // This will return a copy of the object, not the original! function &findMyObjectByName($name) { foreach($this->my_array as $obj) { if($obj->getName() == $name) { return $obj; } } return null; // Not found } ?> To avoid this pitfall, use array_keys(): <? // This will return a reference to the original object. function &findMyObjectByName($name) { foreach(array_keys($this->my_array) as $key) { if($this->my_array[$key]->getName() == $name) { return $my_array[$key]; } } return null; // Not found } ?> ---- Manual Page -- http://www.php.net/manual/en/language.references.whatdo.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39966 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39966&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39966&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#65260) next »