From the course: Learning PHP

What are loops? - PHP Tutorial

From the course: Learning PHP

Start my 1-month free trial

What are loops?

- [Instructor] Sometimes you want to repeat a task until it's done. Practically, this could be looking at all of the records in a file or continuously incrementing a number until you hit the limit you want. The control structures you've seen so far focus on making a decision and then executing code once, but there is a different control structure for if you want to repeat a task some number of times and that's called a loop. Loops will execute a piece of code until some condition becomes false. So you can imagine the structure is like this. While some condition is true, execute some lines of code. If some condition becomes false, exit the loop and move on. there are three different types of loops you'll learn about, but they all have two important components for you to keep in mind. They all must have a true/false condition, like the ones that we saw in if statements and they all must include a statement that moves the condition towards being false. For example, if you have a structure like this where i is one and the condition is i is less than 10, within the code your loop is executing, you should have the statement i plus plus because that increment i and eventually moves the statement i is less than 10 towards being false because i will eventually get to 10, which evaluates to false. If you don't have a condition that moves towards false, you will end up with an infinite loop. These are loops that never terminate and they will crash your website or your application, but luckily, there are a few loops with safeguards to make sure that doesn't happen. So let's take a look at three types of loops in PHP, while loops, for loops and foreach loops.

Contents