|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2003-03-25 10:14 UTC] lev at centers dot ru
<?
// Bag: recursive function corrupt foreach loop
// This bag is near bag #14607 but not equal
//
// ------- description of functions ----------------
// Incorrect function
function out_node1($k,$level)
{
global $name,$ind;
for($i=0;$i<$level;$i++) echo " ";
echo "$name[$k]<BR>\n";
foreach($ind as $i=>$index) {
if($index==$k) out_node1($i,$level+1);
}
}
// Correct function (bypass bag)
function out_node($k,$level)
{
global $name,$ind;
for($i=0;$i<$level;$i++) echo " ";
echo "$name[$k]<BR>\n";
foreach($ind as $i=>$index) {
if($index==$k) $node[]=$i;
}
for($i=0;$i<count($node);$i++) out_node($node[$i],$level+1);
}
//------------------------------------------------------------
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
</head>
<body>
<?
// ------- tree structure ----------------
// Tree: number parrent index
// node1 0 -1
// leaf1 1 0
// leaf2 2 0
// node2 3 0
// leaf3 4 3
// leaf4 5 3
// ------- body of script ----------------
$name=Array('node1','leaf1','leaf2','node2','leaf3','leaf4');
$ind=Array('-1','0','0','0','3','3');
//------------------------------------------------------------
echo "<BR><B>Incorrect example</B><BR>\n";
// print tree
out_node1(0,0);
echo "<BR><B>Correct example</B><BR>\n";
// print tree
out_node(0,0);
?>
</body>
</html>
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Tue Dec 02 08:00:01 2025 UTC |
"Nested foreach" and "recursive function call into foreach loop" is deferent things. I guess: control variable of foreach loop is global and corrupted after recursive function call. Compact variant of example: -------------------------- <? // Bag: recursive function corrupt foreach loop function out_node($k,$level) { global $name,$ind; for($i=0;$i<$level;$i++) echo " "; echo "$name[$k]<BR>\n"; foreach($ind as $i=>$index) { if($index==$k) out_node($i,$level+1); } } ?> <html> <head> </head> <body> <? $name=Array('node1','leaf1','leaf2','node2','leaf3','leaf4'); $ind=Array('-1','0','0','0','3','3'); out_node(0,0); ?> </body> </html> Result: ------- node1 leaf1 must be (Correct result): ------------------------ node1 leaf1 leaf2 node2 leaf3 leaf4