Tutorial for “For” loop

What is For Loops?

The For loop is a control structure that repeatedly executes a block of code until a condition is met. It’s commonly used to make a code block repeat itself a set number of times. It should be used if the number of iterations is given; otherwise, a while loop should be used. You use for loop when you already know how many times you want to run a block of code. It permits users to centralize all comments concerning the loop.

Syntax:-

for (init counter; test counter; increment counter) {
  code to be executed for each iteration;
}

The for loop in PHP is similar to the for loop in Java/C/C++. The following are the definitions of the (for loop) parameters:

  • initialization –It is used to set the counter variables and checked before the body of the loop is executed once unconditionally.
  • condition – At the beginning of each repetition, the state is assessed. The loop remains if it is true and the nesting statements are performed. If it is wrong, the loop is finished.
  • increment – The loop counter adds a new value. It is assessed at the end of every iteration.
php for loop flowchart

Example1:-

Output:-

Example2:-

Output:-

Tagged : / / / / / / /