Re: while question

From: Date: Mon, 17 Nov 2008 14:25:08 +0000
Subject: Re: while question
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-283353@lists.php.net to get a copy of this message
Alain Roger wrote:
Hi, i'm on PHP training and our lector is telling us that to avoid counting an array item amout thanks count($my_array), he tells we can do: while($my_array) { ... do something } but from experience this is an infinity loop... it should be always something like $count = count($my_array); while($i <= $count) { ... do something ... $i++; } has someone already use such syntax ? i mean as the first one. thx.
sounds like a poor teacher, however I have a feeling he simply wants you to be able to count the items in an array without using the count() function. In this case you would be best to use a foreach loop. you are correct in saying that a while($myarray) loop would be infinite, unless you use a function to reduce the array on each iteration of the while loop as such: <?php $myarray = array('a','b','c','d','e','f'); $count = 0; while ( $myarray ) { $count += array_pop($myarray) ? 1 : 0; }; echo $count; ?> but.. get a new teacher :p (no offense)

« previous php.general (#283353) next »