<< PHP Arrays | PHP Tutorials | PHP For Loop >>

PHP While Loop - like a circle?

Yeah exactly like a circle actually. A loop in PHP is just a bunch of repetitive code executions depending on a number of things. In the while loop, it depends on a condition. The code inside the while block will be executed until the condition defined is not met. The condition in the while statement is the same syntax as the if...else statements. Here is is the syntax:

while (condition) {
code to be executed
}

The code to to be executed, like I said above, will be executed until the condition is met.

While Loop Example

Say you were a teacher of younger children, and you had a system that you would get gold stars to your students. Also, that for each gold star they had, they would get 2 pieces of candy. Well you can make a table showing for what stars how much candy they will have (in total):

<?php
$count = 0;
?>
<table border="1" cellpadding="2" cellspacing="0">
<tr>
<th>Star Count</th>
<th>Total Candy</th>
</tr>
<?php
while ($count <= 10) {
?>
<tr>
<td><?php echo $count; ?></td>
<td><?php echo $count * 2; ?></td>
</tr>
<?php
$count++;
}
?>
</table>

This is what the end user will see:

Star Count Total Candy
0 0
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20

If you remember from my other tutorials (which you should, or go back and read them), this will keep executing while $count is less than or equal to 10. Once it goes to 11, it will stop and the rest of the code on the page will execute normally. You'll also see I used the 'hole in the PHP code' method to output the tables. This makes it simpler while outputting HTML.

<< PHP Arrays | PHP Tutorials | PHP For Loop >>