Skip to main content

PHP Loops

By SamK
0
0 recommends
Topic(s)

When writing code, you often need to execute the same block multiple times under certain conditions. Instead of duplicating similar lines, loops are used.

PHP offers several loop types:

  • while: Executes a block of code as long as a specified condition is true.
  • do...while: Executes a block of code once and then repeats the loop as long as a specified condition is true.
  • for: Executes a block of code a specified number of times.
  • foreach: Loops through a block of code for each element in an array.

Now we'll look at each one of them with some examples.

PHP while Loop

The while loop in PHP executes a block of code repeatedly as long as a specified condition remains true.

Example: Print the value of $a while $a is less than 5.

<?php
$a = 2;
while ($a < 5) {
  echo $a . "<br>"; 
  $a++;
}
?>

/*
Output:
2
3
4
*/

Note: In the above example, if  $a is not incremented, the loop will run indefinitely, because the condition $a < 5 will never become false.

The while loop does not run a predetermined number of times. Instead, it checks the condition after each iteration to determine if it should continue running. 

The break Statement

Using the break statement, we can stop the loop even if the condition remains true.

To stop the loop when $a is 4, use the break statement.

<?php  
$a = 2;
while ($a < 5) {
  if ($a == 4) break;
  echo $a . "<br>";
  $a++;
} 
?>

/*
Output:
2
3
*/

The continue Statement

Using the continue statement, we can skip the current iteration and proceed with the next one.

To skip the current iteration and jump to the next iteration if $a is 3, use the continue statement.

<?php  
$a = 0;
while ($a < 5) {
  $a++;
  if ($a == 3) continue;
  echo $a . "<br>";
}
?>

/*
Output:
1
2
4
5
*/

Note:  The break and continue statements work in a similar way for every type of loop.

Alternative Syntax

The syntax for a while loop can also be written using the endwhile statement like this.

Print $a as long as $a is less than 5.

<?php  
$a = 2;
while ($a < 5):
  echo $a . "<br>";
  $a++;
endwhile;
?>

/*
Output:
2
3
4
*/

PHP do while Loop

The do...while loop executes the block of code once, checks the condition afterwards, and repeats the loop while the specified condition remains true.

Print $a while $a is less than 5.

<?php  
$a = 2;
do {
  echo $a . "<br>";
  $a++;
} while ($a < 5);
?>

/*
Output:
2
3
4
*/

Note: In a do...while loop, the condition is tested AFTER executing the statements within the loop. This ensures that the do...while loop will execute its statements at least once, regardless of whether the condition initially evaluates to false. So, the code block executes once, even if the condition is never true.

PHP for Loop

The for loop iterates through a block of code for a specified number of times.

The for loop is employed when the number of iterations for executing the script is known in advance.

Syntax

<?php
for (expression1, expression2, expression3) {
  // code block
}
?>

Here's how it works:

  • expression1 is evaluated once.
  • expression2 is evaluated before each iteration.
  • expression3 is evaluated after each iteration.

Example: Print the numbers from 0 to 5.

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

/*
Output:
The number is: 0
The number is: 1
The number is: 2
The number is: 3
The number is: 4
The number is: 5
*/

Example Explained:

  • The first expression, $x = 0;, initializes the counter to 0.
  • The second expression, $x <= 5;, is evaluated before each iteration. The code block executes only if this expression is true. In this example, it remains true as long as $x is less than or equal to 5.
  • The third expression, $x++;, increments the value of $x by one after each iteration.

PHP foreach Loop

The foreach loop iterates through a block of code for each element in an array or each property in an object.

Example: Iterate through the items of an indexed array.

<?php  
$colors = array("apple", "banana", "orange", "melon");
foreach ($colors as $x) {
  echo "$x <br>";
}
?>
/*
Output:
apple
banana
orange
melon
*/

During each iteration of the loop, the value of the current array element is assigned to the variable $x. The iteration continues until it reaches the last array element.

Keys and Values

The array mentioned above is an indexed array, where the first item has the key 0, the second has the key 1, and so forth.

In contrast, associative arrays use named keys that you assign to them. When iterating through associative arrays, you may want to retain both the key and the corresponding value. This can be achieved by specifying both the key and value in the foreach loop definition, like this:

Example: Print both the key and the value from the $team array.

<?php
$team = array("Alice"=>"29", "Mark"=>"33", "Sophia"=>"41");
foreach ($team as $name => $age) {
  echo "$name is $age years old.<br>";
}
?>
/*
Output:
Alice is 29 years old.
Mark is 33 years old.
Sophia is 41 years old.
*/

The foreach Loop on Objects

The foreach loop can also iterate through properties of an object.

Print the property names and values of the $myFruit object.

<?php
class Fruit {
    public $Name;
    public $Color;
    
    public function __construct($Name, $Color) {
        $this->Name = $Name;
        $this->Color = $Color;
    }
}

$myFruit = new Fruit("Apple", "Red");

foreach ($myFruit as $x => $y) {
  echo "$x: $y<br>";
}
?>

/*
Output:
Name: Apple
Color: Red
*/

Foreach by Reference

When iterating through array items, any changes made to the array item will not affect the original array by default.

<?php
$fruits = array("apple", "banana", "cherry");
foreach ($fruits as &$fruit) {
    if ($fruit == "cherry") $fruit = "mango";
}
var_dump($fruits);
?>
/*
Output:
array(3) { [0]=> string(5) "apple" [1]=> string(6) "banana" [2]=> &string(5) "mango" }
*/

But, by using the & character in the foreach declaration, the array item is assigned by reference, which means that any changes done to the array items inside the loop are done to the original array.

Example

<?php
$animals = array("cat", "dog", "bird");
foreach ($animals as &$animal) {
    if ($animal == "bird") $animal = "parrot";
}
var_dump($animals);
?>
/*
Output:
array(3) { [0]=> string(3) "cat" [1]=> string(3) "dog" [2]=> &string(6) "parrot" }
*/

Alternative Syntax

The foreach loop syntax can also be written using the endforeach statement like this,

Iterate through the items of an indexed array.

<?php
$animals = array("cat", "dog", "elephant");
foreach ($animals as $animal) :
    echo "I have a $animal.<br>";
endforeach;
?>
/*
Output:
I have a cat.
I have a dog.
I have a elephant.
*/

Questions & Answers