note 53941 added to control-structures.foreach

From: Date: Fri, 17 Jun 2005 18:24:06 +0000
Subject: note 53941 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-90596@lists.php.net to get a copy of this message
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. ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+53941 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+53941&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+53941&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+53941&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+53941&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+53941&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+53941&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+53941&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#90596) next »