#24646 [Opn->Bgs]: foreach doesnt work well inside recursive functions

From: Date: Mon, 14 Jul 2003 17:58:14 +0000
Subject: #24646 [Opn->Bgs]: foreach doesnt work well inside recursive functions
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-43970@lists.php.net to get a copy of this message
ID: 24646 Updated by: sniper@php.net Reported By: sagi at boom dot org dot il -Status: Open +Status: Bogus Bug Type: Arrays related Operating System: Linux PHP Version: 4CVS-2003-07-14 (stable) New Comment: Please read the "Note:"'s from http://www.php.net/foreach as this is not any bug. Previous Comments: ------------------------------------------------------------------------ [2003-07-14 09:42:30] sagi at boom dot org dot il Description: ------------ I'm trying to write a recursive function that uses foreach() on the same array couple of times simultaneously. However it looks like when going back to the original function foreach doesn't continue where it stopped, but just continues running the code after the foreach. I tried the same with for() and it works right. in the attached code there are the 2 lines that you can comment out to see how it works with for() (comment foreach if you do). Reproduce code: --------------- <?php $cats = array( 1 => array(0, 'parent 1'), 2 => array(0, 'parent 2'), 3 => array(0, 'parent 3'), 4 => array(1, 'sub1 of parent 1'), 5 => array(1, 'sub2 of parent 1'), 6 => array(2, 'sub1 of parent 2'), 7 => array(2, 'sub2 of parent 2'), 8 => array(1, 'sub3 of parent 1'), 9 => array(5, 'sub1 of parent 5'), 10 => array(2, 'sub3 of parent 2') ); function showit($parent, $level) { global $cats; foreach ($cats as $id => $category) { // for ($id=1; $id <= count($cats); $id++) { // $category =& $cats[$id]; if ($category[0] == $parent) { print str_repeat("\t",$level).'('.$id.') '.$category[1]."\n"; showit($id, $level+1); } } } showit(0, 0); ?> Expected result: ---------------- (1) parent 1 (4) sub1 of parent 1 (5) sub2 of parent 1 (9) sub1 of parent 5 (8) sub3 of parent 1 (2) parent 2 (6) sub1 of parent 2 (7) sub2 of parent 2 (10) sub3 of parent 2 (3) parent 3 Actual result: -------------- (1) parent 1 (4) sub1 of parent 1 ------------------------------------------------------------------------ -- Edit this bug report at http://bugs.php.net/?id=24646&edit=1

« previous php.bugs (#43970) next »