note 53941 deleted from control-structures.foreach by felipe

From: Date: Tue, 29 Jan 2008 11:24:50 +0000
Subject: note 53941 deleted from control-structures.foreach by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-135524@lists.php.net to get a copy of this message
Note Submitter: mike at invertedmind dot com ---- One great use of foreach is for recursive function calls. It can handle things that would otherwise need to be hand-coded down to the desired level, which can make for hard-to-follow nesting. <? /* May you never be forced to deal with a structure like this in real life... */ $items = array( -1, 0, array( array(1,2,3,4), array(5,6,7,8), array(9,10,11,12) ), array( array("a", "b", "c"), array("d", "e", "f"), array("g", "h", "i") ) ); print_array($items, 0); function print_array($arr, $level) { $indent = str_repeat("&nbsp;", $level * 4); foreach ($arr as $item) { if (is_array($item)) { print $indent . "Item is an array...<br>\n"; print_array($item, $level + 1); } else print $indent . "Value at current index: " . $item . "<br>\n"; } } ?> This will output: Value at current index: -1 Value at current index: 0 Item is an array... Item is an array... Value at current index: 1 Value at current index: 2 Value at current index: 3 Value at current index: 4 Item is an array... Value at current index: 5 Value at current index: 6 Value at current index: 7 Value at current index: 8 Item is an array... Value at current index: 9 Value at current index: 10 Value at current index: 11 Value at current index: 12 Item is an array... Item is an array... Value at current index: a Value at current index: b Value at current index: c Item is an array... Value at current index: d Value at current index: e Value at current index: f Item is an array... Value at current index: g Value at current index: h Value at current index: i And it could recurse as far as you want it to go.

« previous php.notes (#135524) next »