PHP for Loop

Summary: in this tutorial, you will learn about PHP for loop statement to execute a block of code predetermined number of times.

Introduction to PHP for loop

The for loop statement is the most complex loop statement in PHP. You often use the PHP  for loop statement when the number of executions is predetermined. Even though, the PHP for loop statement provides more functionality than that.

If you want to execute a code block based on a given condition, you can use while loop or do while loop statement.

The following illustrates the for loop statement syntax:

Let’s examine the syntax of the for loop statement in greater detail:

  • The init_expr expression always is evaluated once when the for loop statement is first reached. You typically use init_expr to initialize a loop counter variable.
  • The condition_expr is evaluated at the beginning of each iteration. This condition expression is used to control whether the loop continues or not. If the condition expression evaluates to true, the loop continues. If it evaluates to false, the loop is terminated. For example, you can use the condition_expr to test the loop counter
  • The increment_expr  expression is evaluated at the end of each iteration. It is often used to change the loop counter variable.
  • You can omit any expression: init_expr, condition_expr and increment_expr expression, as long as you keep the semicolon( ;)

PHP for Loop

Let’s take a look at some examples of using the PHP  for loop statement.

PHP for loop examples

The following example counts from 1 to 5, and displays the current counter’s value in each iteration.

We initialized the counter variable $i to 1 at the beginning of the loop. In each iteration, we display the counter’s value and also increase its value by 1. The condition expression checks if $i is less than 5.  If the result of the evaluation is true, the loop continues. Once the value of $i variable reaches 5, the loop is terminated.

As mentioned above, you can omit any expression in the for loop statement as long as you keep the semicolon (;). See the following example:

We omitted all expressions in the for loop statement. Inside the loop, we get a random number whose value is between 1 and 5 by using the rand() function and display the number. If the random number is 2, we terminate the loop by using the  break statement.

In case you want to mix PHP and HTML code, you can use the colon syntax of the for loop statement as the following example:

In the example, we used the for loop statement to generate an unordered list of 5 list items.

In this tutorial, you have learned how to use the PHP for loop statement to execute a block of code a predetermined number of times.

  • Was this tutorial helpful ?
  • YesNo