From: sagi at boom dot org dot il
Operating system: Linux
PHP version: 4CVS-2003-07-14 (stable)
PHP Bug Type: Arrays related
Bug description: foreach doesnt work well inside recursive functions

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 bug report at [url]http://bugs.php.net/?id=24646&edit=1[/url]
--
Try a CVS snapshot (php4): [url]http://bugs.php.net/fix.php?id=24646&r=trysnapshot4[/url]
Try a CVS snapshot (php5): [url]http://bugs.php.net/fix.php?id=24646&r=trysnapshot5[/url]
Fixed in CVS: [url]http://bugs.php.net/fix.php?id=24646&r=fixedcvs[/url]
Fixed in release: [url]http://bugs.php.net/fix.php?id=24646&r=alreadyfixed[/url]
Need backtrace: [url]http://bugs.php.net/fix.php?id=24646&r=needtrace[/url]
Try newer version: [url]http://bugs.php.net/fix.php?id=24646&r=oldversion[/url]
Not developer issue: [url]http://bugs.php.net/fix.php?id=24646&r=support[/url]
Expected behavior: [url]http://bugs.php.net/fix.php?id=24646&r=notwrong[/url]
Not enough info: [url]http://bugs.php.net/fix.php?id=24646&r=notenoughinfo[/url]
Submitted twice: [url]http://bugs.php.net/fix.php?id=24646&r=submittedtwice[/url]
register_globals: [url]http://bugs.php.net/fix.php?id=24646&r=globals[/url]
PHP 3 support discontinued: [url]http://bugs.php.net/fix.php?id=24646&r=php3[/url]
Daylight Savings: [url]http://bugs.php.net/fix.php?id=24646&r=dst[/url]
IIS Stability: [url]http://bugs.php.net/fix.php?id=24646&r=isapi[/url]
Install GNU Sed: [url]http://bugs.php.net/fix.php?id=24646&r=gnused[/url]