note 52733 added to control-structures.while
| From: | stuart at osu1 dot php dot net | Date: | Wed, 11 May 2005 09:06:30 +0000 |
| Subject: | note 52733 added to control-structures.while | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-89251@lists.php.net to get a copy of this message | ||
A note to anyone nesting a while loop inside a while loop....
Consider the example below:
$one = array("10", "20", "30", "40");
$two = array("a", "b", "c", "d");
$i=0;
while($i < count($one)) {
while($a = each($two)) {
echo $a[1]." - ".$one[$i].", ";
}
$i++;
}
This will return the following:
a - 10, b - 10, c - 10, d - 10
So in effect the main while loop is only doing one iteration... and not 4 as expected....
Now the example below works as expected..
$i=0;
while($i < count($one)) {
foreach($two as $a) {
echo $a." - ".$one[$i]."\n";
}
$i++;
}
by returning:
a - 10, b - 10, c - 10, d - 10, a - 20, b - 20, c - 20, d - 20, a - 30, b - 30, c - 30, d - 30, a -
40, b - 40, c - 40, d - 40
So there is clearly a difference on how while statements work in comparison to other looping
structures.
I think it would be good to have an explaination of this strange behaviour.
----
Manual Page -- http://www.php.net/manual/en/control-structures.while.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+52733
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+52733&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+52733&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+52733&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+52733&report=yes&reason=useless
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+52733&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+52733&report=yes
Search -- http://master.php.net/manage/user-notes.php