Re: Infinite loop with for(), sizeof()
| From: | David Robley | Date: | Mon, 24 Jul 2000 04:44:25 +0000 |
| Subject: | Re: Infinite loop with for(), sizeof() | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-7821@lists.php.net to get a copy of this message | ||
On 23 Jul, Steve Chadsey wrote:
> Hello,
>
> I'm wondering what I'm doing wrong here, with the following code:
>
> ---[start]-----
> <?
> $names[0] = "Hello World ";
>
> for($i = 0;$i <= sizeof($names); $i++) {
> print $i . "<br>\n";
> $names[$i] = trim($names[$i]);
> }
> ?>
> ---[end]-----
>
> It runs until I stop it.
> It does this with PHP/4.0.1pl2 on both a Solaris 2.6 box and a Linux
> 2.2.14 box, both with apache 1.3.12.
>
> If no one else can reproduce this, then I'll feel really bad.
>
> --
> Steve Chadsey <schadsey@anathema.lightbridge.com>
> Now playing: Time Is Coming
> (Testament - "Practice What You Preach")
>
Don't feel bad - it can be reproduced. However it's no bug - you have
forgotten that your array subscripts start at 0, but the sizeof gives
you the number of elements in the array - always greater than zero if
the arrray is not empty.
Effectively, what you are doing here is adding an element to the array
with each iteration after the first; thus sizeof($names) increases by
one each iteration, as does $i where you increment it; thus $i will
never be greater than sizeof($names).
The solution is to modify the control structure as follows:
for($i = 0;$i < sizeof($names); $i++) {
Cheers
--
David Robley | WEBMASTER & Mail List Admin
RESEARCH CENTRE FOR INJURY STUDIES | http://www.nisu.flinders.edu.au/
AusEinet | http://auseinet.flinders.edu.au/
Flinders University, ADELAIDE, SOUTH AUSTRALIA