What happens is (if I understand it correctly):

First, PHP sets $i to equal 0, and then immediately sets $i to $months_arr_length.

Every time the loop executes, it resets $1 to $months_arr_length, so you are stuck in an infinite loop.

The reason behind this is you are using assignment equals (=) instead of comparison equals(==). It's a mistake I've made myself quite a few times.

As an aside, a neater way of using a for loop on an array is the following:

foreach ($months_arr as $key => $value)
{
        echo $value."<br />";
}



On 8 Dec 2004, at 22:41, R. Van Tassel wrote:

I have a question about the following code:

**********************************************

$months_arr = array("JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG",
"SEP", "OCT", "NOV", "DEC");
$months_arr_length = count($months_arr);


for($i = 0; $i = $months_arr_length; $i++){
        echo $months_arr[1]." <br />";
}

***********************************************

When I run the code above it continues and never stops. According to the PHP
documentation the second condition works as follows:


"In the beginning of each iteration, expr2 is evaluated. If it evaluates to
TRUE, the loop continues and the nested statement(s) are executed. If it
evaluates to FALSE, the execution of the loop ends."


In the first iteration of the loop $i would equal 0 and the array length is
12. 12 is consistent. To it seems that the loop should STOP when the counter
reaches 12, equal to the length of the array. Why is it continuing in a
neverending loop? What am I missing?


Changing the condition of the for loop to $i <= $months_arr_length; fixes
everything and it works properly.


Can someone please explain where my confusion is?

Thanks,
~R. Van Tassel

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


-- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php



Reply via email to