How do you make a counter using a while loop in php?

Brian

New member
I need to fix logic flaws in a php while loop. The final result is supposed to have an array with the numbers 1 through 100 filled then displayed on the screen. This is code with the flaws:

<?php
$Count = 0;
while ($Count > 100) {
$Numbers[] = $Count;
++$Count;
foreach ($Count as $CurNum)
echo "<p>$CurNum</p>";
}
?>
 
1. $Count is a number, while the array is called $Numbers.
2. $Count is never greater than 100, so you need to change that to a less than.
3. This code will give you 0-99, not 1-100.
4. Your output is inside of the array-filling while loop, so you'll get an output like 1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, etc.

See if this works:

<?php
$Count =1;
while ($Count < 101) {
$Numbers[] = $Count;
++$Count;
}
foreach ($Numbers as $CurNum)
echo "<p>$CurNum</p>";
?>
 
Back
Top