PHP for loop (s) are designed to work with iterative numbers. A block of code will be executed for a specified number of times.

PHP for Loop :

The PHP for loop demands that the programmer must know how many times the script is needed to run.

Syntax :

for (initialize counter; test counter; increment counter) {
Block of code for execution;
}

The php for loop parameters in the syntax are detailed below :

Initialize counter: Declares the first value of the counter

Test counter: Declares the condition to be tested. The loop runs for as long as this condition is true.

Increment counter: increments the initialized value each time the loop runs until the parameter is test counter parameter is false.

PHP for loop Example :

<?php

for ($i = 0; $i <= 5; $i++) {
echo "I am running $i time(s)<br>";
}
?>

Output:

I am running 0 time(s)
I am running 1 time(s)
I am running 2 time(s)
I am running 3 time(s)
I am running 4 time(s)
I am running 5 time(s)

PHP foreach Loop :

PHP for loops and other loops are applicable for all kinds of variables. PHP foreach loops are specifically meant for the arrays in PHP.

The PHP foreach loop loops through the elements or key/value pairs in arrays.

foreach Syntax :

foreach ($array as $value) {
Code for execution within an array;
}

Every loop iteration targets an element of an array until every member is assigned/modified.

Example :

<?php

$cars = array("BMW", "Maybach", "Tata", "Mitsubishi");

foreach ($cars as $brand) {
echo "$brand <br>";
}
?>

Output:

BMW
Maybach
Tata
Mitsubishi

The for loops and foreach loops have great applicability in any situation. As stated in the previous tutorials, PHP gives the developer all tools that he will require to exploit his /her creativity.

Happy Learning 🙂