Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 5 / 68

Loops (for statements)

In this lesson you will learn how to repeat work with a for statement in PHP so you can run the same logic efficiently. This is for anyone searching for "PHP for loop how to use".

A for statement repeats the same work. Instead of writing the same lines over and over, a few lines express a large number of repetitions - that is the power of a loop. Paired with foreach, working with arrays gets easier still.

The sample code prints the numbers 1 through 5 using for ($i = 1; $i <= 5; $i++). Notice that the loop variable $i also needs its $, and that the three parts of the loop (start, condition, update) are separated by semicolons.

A common stumbling block for beginners is forgetting the update part ($i++) and creating an infinite loop. If your browser or program seems to freeze, check the condition and the update first. Confusing it with foreach and trying to use it on non-arrays is another frequent slip.

Paired with foreach, iterating over the elements of an array or a collection becomes simple too. In real PHP code, foreach is often used more frequently than a plain for loop.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)