The PHP loop is a repetition for a collection or a compound of data to expose the contents. And that can be done using PHP loops such as foreach, while loop, for loop, let’s see examples.

The PHP loop works according to some sequence, let’s see how it does work.

How the PHP Loop Works

Normally, the loops are working according to the compound data or the list, as I mentioned before. And each loop, it brings another following row from the collection according to the index in the list.

PHP Loop | How to Extract Data using PHP Loops with Examples

In this figure, the loop withdraws the rows one by one from the compound data according to its index. So it starts with 0 row and doing another loop over the compound again to get the following row number 1 and then going to get the following one and so on.

Once it reaches the final row, it will end the loop directly because there is no data else.

This is the concept of the loop for all programming languages. But how to do that with PHP?

Actually, PHP has many loop types, let’s see that in-depth with the following section.

PHP Loops Examples

Before starting in PHP loops examples, you have to take a look at the following loop types to understand how they work.

Loop TypeDescription
forIt loops according to the number or index that can be specified in the for loop
foreachIt loops according to compound element to allow access the $key and $value
whileLoops according to the condition block if it has a false it will end the loop immediately
do whileIt doing one loop before the condition and then loops according to the result of block condition

Anyway, Let’s see examples for each one.

PHP for loop example.

<?php 
  
   $site    = "codedtag.com";
   $pattern = "";
   
   for( $i = 0; $i < strlen($site); $i++ ) {
     $pattern .= $site[$i];
     if ( $i != ( strlen($site) - 1 ) ) {
       $pattern .= " - ";
     }
   }
   
   echo $pattern;

?>

The output:

C - o - d - e - d - T - a - g - . - c - o - m

PHP foreeach loop example.

<?php 
  
   $user_info = array(
      "country" => "Netherlands",
      "name"    => "Peter David",
      "job"     => "Software Engineer"
   );
  
   foreach( $user_info as $key => $value ) {
      echo ucfirst($key);
      echo " : ";
      echo $value;
      echo "\n";
   }
   

?>

The output:

Country : Netherlands
Name : Peter David
Job : Software Engineer

PHP while loop example.

<?php 

   $f = 0;
   while( $f <= 10 ) {
     echo $f;
     echo "\t"; // tab
     $f++;
   }

?>

The output:

0 1 2 3 4 5 6 7 8 9 10

PHP do while loop example.

<?php 
   
   $z = 3;

   do {
      echo "This is line number {$z} \n";
      $z++;
   } while ( false );
 
?>

The output:

This is line number 3

Wrapping Up

In this article, you learned about how the PHP loop works and saw many types of the PHP Loops with examples.