note 95221 added to control-structures.foreach

From: Date: Sat, 19 Dec 2009 12:31:26 +0000
Subject: note 95221 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-164131@lists.php.net to get a copy of this message
There is currently no syntax to write a single yet lazy-evaluated foreach thru multiple arrays, but you can double-foreach like this (this is not lazy-evaluated yet): <?php foreach (array ($array1, $array2, $array3) as $control) foreach ($control as $item) echo $item; ?> The above will echo all items from all three input arrays. Note that simple array_merge might not always work (sicne array_merge might depend on the type of array keys) and might consume more memory in the process. The reasonable grounds for doing this might be a more complicated body of the foreach, which you do not want to repeat in your code for every input array, or a fact that you got too many input arrays. Now, a lazy-evaluation trick would look something like this (although php is capable of optimizations that fully neglect reasons for doing things like this): <?php foreach (array ('array1', 'array2', 'array3') as $control) foreach ($$control as $item) echo $item; ?> And finally, a lazy-evaluation trick that might be reasonable: <?php foreach (array ('expr1', 'expr2', 'expr3') as $control) foreach (eval ($control) as $item) if ($item) break 2; else echo $item; ?> Example (searching for a non-trivial value): <?php // search for a child name $seachName = 'Jozko'; // prepare the sources $sources = array ( '$item1->GetChilds()', '$item2->GetChilds()', '$item3->GetParent()->GetChilds()', '$item3->GetComputeSomethingDifficultChilds()', ); // search in several different arrays foreach ($sources as $control) foreach (eval ($control) as $child) if ($child->GetName() == $seachName) break 2; // now we got the correct child // and we did it in lazy-evaluation style print_r ($child); ---- Server IP: 69.147.83.197 Probable Submitter: 195.91.79.25 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/95221 Del: integrated -- https://master.php.net/note/delete/95221/integrated Del: useless -- https://master.php.net/note/delete/95221/useless Del: bad code -- https://master.php.net/note/delete/95221/bad+code Del: spam -- https://master.php.net/note/delete/95221/spam Del: non-english -- https://master.php.net/note/delete/95221/non-english Del: in docs -- https://master.php.net/note/delete/95221/in+docs Del: other reasons-- https://master.php.net/note/delete/95221 Reject -- https://master.php.net/note/reject/95221 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#164131) next »