Basic Loops
Now we are going to start to get into loops and iteration. Loops are used to repeat a block of code a certain number of times. This is useful when you want to do something a certain number of times, or when you want to do something for each item in an array.
The reason that I want to jump into this now is because we just looked at arrays, and arrays are a great use case for loops. We can use loops to iterate over each item in an array and do something with it.
We will get into looping over arrays soon, but I just want to show you some basic loops first.
The for Loop
The for loop is traditionally the most common type of loop. It is used to repeat a block of code a certain number of times. Let's look at an image to help explain how it works:
It takes three parameters
- Initialization: This is where you set the starting value of the loop.
- Condition: This is where you set the condition that must be met for the loop to continue.
- Update Expression/Increment: This is where you set how to update the loop variable each time the loop runs. In many cases you increment the loop variable by 1 each time the loop runs, so it is also called the increment or increment expression.
Let's create a very simple loop that will run 10 times and display the value of the loop variable each time.
for ($i = 0; $i < 10; $i++) {
echo $i; // 0123456789
}
We start by setting the loop variable to 0. Then we set the condition to run the loop as long as the loop variable is less than 10. Then we increment the loop variable by 1 each time the loop runs.
It only goes to 9 because the condition is that the loop variable must be less than 10. Once it gets to 10, the condition is no longer true, so the loop stops. We can change it to include 10 by changing the condition to less than or equal to 10.
for ($i = 0; $i <= 10; $i++) {
echo $i; // 012345678910
}