note 39966 deleted from language.references.whatdo by colder

From: Date: Sat, 24 Feb 2007 11:45:52 +0000
Subject: note 39966 deleted from language.references.whatdo by colder
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-123820@lists.php.net to get a copy of this message
Note Submitter: jazfresh at hotmail dot com ---- 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 } ?>

« previous php.notes (#123820) next »