RCRAMER.COM
Clever website slogan
Home > Tech > PHP

PHP Loops

In PHP, we have the following looping statements:

  • for - loops through a block of code a specified number of times
  • foreach - loops through a block of code for each element in an array
  • while - loops through a block of code while a specified condition is true
  • do...while - loops through a block of code once, and then repeats as long as specified condition is true

For Loops

For loops execute a block of code a specified number of times, or while a specified condition is true. The for loop is used when you know in advance how many times the code should run.

for (init; condition; increment) { code to be executed; } Where:
  • init: Mostly used to set the counter (but can be any code to be executed once at the beginning of the loop).
  • condition: Evaluated for each loop iteration. If it evaluates to TRUE, the loop continues. If it evaluates to FLASE, the loop ends.
  • increment: Mostly used to increment a counter (but can be any code to be executed at the end of the loop)
CodeOutput
<?php
for ($i=1; $i<5; $i++) {
  echo "The number is " . $i . "<br />";
}
?>
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Foreach loops

The foreach loops is used to loop through arrays.

foreach ($array as $value) { code to be executed; }

For evey loop iteration, the value of the current array element is assigned to $value (and the array pointer is moved by one) - so on the next loop iteration, you'll be looking at the next array value.

CodeOutput
<?php
$x=array("one","two","three");
foreach ($x as $value) {
  echo "$value . "<br />";
}
?>
one
two
three

While Loops

The while loop executes a block of code while a condition is true.

while (condition) { code to be executed; }
CodeOutput
<?php
$i=1;
while($i<=5) {
  echo "The number is " . $i . "<br />";
}
?>
The number is 1
The number is 2
The number is 3
The number is 4
The number is 5

Do...While Loops

The do...while loop will always execute a block of code once, it will then check the condition, and repeat the loop while the condition is true.

do { code to be executed; } while (condition)
CodeOutput
<?php
$i=1;
do {
  $i++
  echo "The number is " . $i . "<br />";
  }
while($i<=5)
?>
The number is 2
The number is 3
The number is 4
The number is 5
The number is 6