note 95221 deleted from control-structures.foreach by googleguy

From: Date: Wed, 14 Nov 2012 22:26:43 +0000
Subject: note 95221 deleted from control-structures.foreach by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191959@lists.php.net to get a copy of this message
Note Submitter: jsimlo at yahoo dot com ---- 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);

« previous php.notes (#191959) next »