PHP for: Explained with 2 examples

The for loop in PHP

Loops are the way to execute specified block of code again and again to a given number of times. There will be many scenarios in programming life when you need one or the other type of loop in order to achieve a task.

A Short video of for loop

See an example of for loop

Types of loops in PHP

Four types of loops are supported in PHP:

  1. The for loop
  2. while loop
  3. do…while loop
  4. foreach – loop

This chapter will discuss PHP For loop only. The for loop, also known as iteration statement is generally used when you know the number of iterations in loops.

Structure of for loop

Following is the general structure of PHP for loop:

for ( initialization; condition; increment the counter){

Code to be executed;

}

  • The first parameter in for loop PHP sets a counter initial value.
  • The second parameter tells until when code should be executed.
  • The Third parameter increments/decrements a counter.
  • Execute the code within the for loop enclosed in curly braces.

Example of for loop in PHP

In the following example, a variable i is initialized with a value of 0.  The loop iterates through until the value of the variable i reaches 5. In each iteration, the variable will be incremented by 1.

In the curly braces, we used a print statement to display the current value of i. See the example by clicking the link below or copy/paste the code in your editor:

PHP for loop

Experience this example online

For loop – more real example

Following example mixes HTML with for loop to generate HTML table as the output with Quantity and price headers.

PHP for loop html

Experience this example online

 

Following are the links to other loop types in PHP.

While Loop | Do While Loop | Foreach Loop