php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #24646 foreach doesnt work well inside recursive functions
Submitted: 2003-07-14 09:42 UTC Modified: 2003-07-14 12:58 UTC
Votes:1
Avg. Score:5.0 ± 0.0
Reproduced:1 of 1 (100.0%)
Same Version:1 (100.0%)
Same OS:0 (0.0%)
From: sagi at boom dot org dot il Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 4CVS-2003-07-14 (stable) OS: Linux
Private report: No CVE-ID: None
View Add Comment Developer Edit
Welcome! If you don't have a Git account, you can't do anything here.
You can add a comment by following this link or if you reported this bug, you can edit this bug over here.
(description)
Block user comment
Status: Assign to:
Package:
Bug Type:
Summary:
From: sagi at boom dot org dot il
New email:
PHP Version: OS:

 

 [2003-07-14 09:42 UTC] 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


Patches

Add a Patch

Pull Requests

Add a Pull Request

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2003-07-14 12:58 UTC] sniper@php.net
Please read the "Note:"'s from http://www.php.net/foreach
as this is not any bug.

 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Thu Mar 28 10:01:26 2024 UTC