PHP Tutorial: PHP Loops

PHP Loops

In Php, we have the following loops.

  • while - loops through a block of code as long as the specified condition is true
  • do...while - loops through a block of code once, and then repeats the loop as long as the specified condition is true
  • 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

PHP while Loops:-

While loop executes the block of code as long as the condition is true. If it found the false then it  break the execution.

Syntax:

<?php

while (condition is true) {
         code to be executed;
}

?>

Example:-

<?php

$x = 2;
while($x <= 8) {
      echo "The number is: $x  <br>";
      $x++;
}

?>

Output:-
The number is: 2 
The number is: 3 
The number is: 4 
The number is: 5 
The number is: 6
The number is: 7
The number is: 8

The PHP do...while Loop:-

The do..while loop executes once in every case. After excute once it checks the conditions and work just like simple while loop.

Syntax:

do {
      code to be executed;
} while (condition is true);

Example:-

<?php

$x = 12;
do {
      echo "The number is: $x <br>";
     $x++;
} while ($x <= 8);

?>

Output:
The number is: 2 
The number is: 3 
The number is: 4 
The number is: 5 
The number is: 6 
The number is: 7 
The number is: 8 
 

PHP  for Loops:-
PHP for loops execute a block of code a given number of times.
The for loop is used when you have how many times you want to execute any code.

Syntax:-

for (init counter; condition; increment counter) {
     code to be executed;
}

Parameters:

init counter: Initialize the loop counter value
conditon: Evaluated for each loop iteration. If it is TRUE, the loop continues. If it is FALSE, the loop ends.
increment counter: Increases the loop counter value

Example:-

<?php

for ($x = 1; $x <= 5; $x++) {
      echo "The number is: $x <br>";
}

?>

Output:
The number is: 1 
The number is: 2 
The number is: 3 
The number is: 4 
The number is: 5 

The PHP foreach Loop:-

The foreach loop works similar to the for loop. It is only works for array. It is used to getting the key values from an array.

Syntax:

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

Example:-

<?php

$colors = array("apple", "banana", "cherry", "mango");
foreach ($colors as $value) {
          echo "$value <br>";
}

?>

Output:
apple 
banana 
cherry 
mango 

Next Topic