PHP for Loops

Unlike the while loop, the for loop is used when you know beforehand how many times you want to execute the codes. The loop is terminated once the number of iterations surpasses the maximum number specified. Here is how it works.


for (initial value; conditional statement;increment/decrement)
     Code to execute;


At the beginning of the statement, you need to specify the counter's initial value. In the next part, the conditional expression is checked; as long as the condition is true, the loop keeps executing the lines of code inside the loop. At the end of the expression, the counter is incremented or decremented.

In the following example, the variable $var is initialized with the value $var=1, which is counter, and its value is used inside the loop. It displays the Hello World text five times.


echo "$var. Hello World!<br>";



Output: 1. Hello World 2. Hello World 3. Hello World 4. Hello World 5. Hello World

or loop, in particular, helps iterate through the array. Here is an example that prints weekday names.


$days = array('Sunday', 'Monday', 'Tuesday', 'Wednesday','Thursday','Friday', 'Saturday');
for ($i = 0; $i < count($days); $i++) {
  echo $array[$i];


Terminating Loops

Using a break statement, you can terminate a loop anytime.