📖 PHP Loops

Loops allow programs to execute statements repeatedly for a given number of times or until a condition is met. There are 2 types of repetition statements in PHP.

for loops
code is executed over and over again for a specified number of times.
  • Always uses a counter.
  • Counter is initialized, evaluated and incremented within the for statement itself.
  • Use when you know how many times you want to execute the code.
Format
<?php
for (initialize variable; relational expression; increment variable) {
	statements to repeat;
}
?>
Example
<?php
$count = 10;
for ($i = 0; $i < $count; $i++) {
	print "$i <br> \n";
}
?>

The print statement will be repeated as long as $i is less than $count. After each iteration, $i is incremented by 1 automatically. This loop would print the numbers 0 through 9.

while loops
code is executed over and over again as long as a certain condition is true.
Format
<?php
while (conditional expression) {
	statements to repeat;
}
?>
Example
<?php
$i = 0;
while ($i < 10) {
	print "$i <br> \n";
	i++;
}
?>

The print statement and increment statements will be repeated as long i is less than 10. When the condition becomes false, then the loop will end and the next statement will be executed. Notice that the while loop does not initialize the counter variable or increment it. If we want to use a counter, we must initialize and increment it ourselves.

Important Rules to Remember
  • Counters must be initialized before beginning the loop.
  • Something must happen inside the loop that will eventually trigger the loop to stop - otherwise infinite loop.