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)

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

Reply via email to