PHP Tutorial


What are PHP loops and how to use them

Loops in PHP are used when we want to run a block of code in a repetitive way, while having control over the repetition.

A loop structure runs based on a condition, while that conditions is true (for example the loop number is less than 5) the loop process will continue. When the condition will be false the execution will stop.

In PHP there are four types of loop statements: while, do ... while, forforeach. In this chapter we will discuss about the first three of them, as the foreach loops are using a specific type of variables (named arrays) that we will discuss in the next chapter.

Why do we use/need loops?

In programming there are many times when we want to execute a block of code multiple times. We can make this process easier by writing the code one time and then use a loop structure to repeat that block of code as many times as we want.

For example we may have a table with all our users and we want to send a newsletter to all of them. One way to this would be to write some code that send an email with the newsletter to one user and them repeat that code for all our users. 

Why do we need loops?