Table of Contents
Loops are a fundamental feature of programming languages. They enable you the ability to run the same code over and over again in a compact syntax.
Loops are used to control the flow of your program and if you find yourself needing to copy and paste functions to keep executing them, perhaps you need to take advantage of loops.
For Loop
A for loop is a loop that consists of three major parts.
- Initial Value: This is where we define the loop's counter variable and assign it an initial value, typically named
i
. - Condition: This is the expression that is evaluated to determine if the loop should run again.
- Iteration: This is the operation to be done at every iteration and is how you progress further with your loop.
Let's take a look at loops by printing out the numbers 1 to 10:
PHP<?php
for ($i = 1; $i <= 10; $i++) {
echo($i . ' ');
}
?>
HTML1 2 3 4 5 6 7 8 9 10
First we create a new variable $i
and we assign it a value of 1
, like so:
PHP$i = 1;
Now we define our loop to keep looping until that variable's value as long as the variable's value remains less than or equal to 10
, found here:
PHP$i <= 10
Finally, after the loop successfully iterates, we increment the value of $i
to ensure that we only go a single number at a time and that the loop eventually ends.
At each iteration from 1 to 10, we are simply echoing the value of $i
plus a space at the end. This gives us the expected final results we saw earlier.
While Loop
A while loop is another loop you may use to execute code over and over again. Compared to a for loop, a while loop is simpler in syntax but otherwise accomplishes the same task. For a while loop, you only need to provide it with a condition that it will evaluate at every iteration to determine if it needs to run again or not. If the condition returns true
, it will run again, but otherwise it will stop running.
Let's repeat the last example using a while loop:
PHP<?php
$i = 1;
while ($i <= 10) {
echo($i . ' ');
$i++;
}
?>
HTML1 2 3 4 5 6 7 8 9 10
The output is the same but we accomplished it using a different loop. First we declared a new variable, i
, and initialized it to 1
.
PHP$i = 1;
Now we want our while loop to continue looping as long as the variable's value is less than or equal to 10
, which we do like so:
PHPwhile ($i <= 10) {
Now we both do what we need to do inside the loop while also incrementing the value of $i
so that its value eventually reaches 11
terminating the loop:
PHPecho($i . ' ');
$i++;
Do While
A do while loop operates the same way as a normal while loop except that the condition to be tested to determine if the loop should iterate again is done after the code block, not before. This means that with a do while loop, your code is guaranteed to run at least one time.
Let's illustrate this by writing a program that simulates you eating pizza:
PHP<?php
$slices = 8;
do {
echo('With ' . $slices . ' left, I shall eat one.');
$slices--;
} while ($slices > 0);
echo('I have ran out of pizza!');
?>
HTMLWith 8 left, I shall eat one.
With 7 left, I shall eat one.
With 6 left, I shall eat one.
With 5 left, I shall eat one.
With 4 left, I shall eat one.
With 3 left, I shall eat one.
With 2 left, I shall eat one.
With 1 left, I shall eat one.
I have ran out of pizza!
First, we initialize a variable to hold the slices of pizza:
PHP$slices = 8;
Then, since we know there is definitely pizza available, we help ourselves to a slice inside the do code block:
PHPdo {
echo('With ' . $slices . ' left, I shall eat one.');
$slices--;
Now that we've eaten a slice, we check to see if there is anymore slices left. If so, we can repeat the loop and eat another one. Otherwise, we ran out and cannot eat anymore:
PHP} while ($slices > 0);
Foreach Loop
A foreach loop is a loop that iterates once for every element, or item, in an array. If you're unfamiliar with what an array is, there's a lesson on that, but for now you can consider it a list of items.
PHP<?php
$languages = ['English', 'French', 'Spanish'];
foreach ($languages as $language) {
echo('I can speak ' . $language);
}
?>
HTMLI can speak English
I can speak French
I can speak Spanish
If your array contains key and value pairs as elements, a foreach loop can also iterate over that as well:
PHP<?php
$languages = [
'English' => 'England',
'French' => 'France',
'Spanish' => 'Spain'
];
foreach ($languages as $language => $country) {
echo($language . ' originated in ' . $country);
}
?>
HTMLEnglish originated in England
French originated in France
Spanish originated in Spain
Break
The break statement can be used inside any loop. When used, it stops the iteration of the loop entirely, no matter what the condition of the loop is.
Let's try counting from 1
to 10
but break after the number 5
.
PHP<?php
$i = 1;
while ($i <= 10) {
echo($i . ' ');
if ($i == 5) {
break;
}
$i++;
}
?>
HTML1 2 3 4 5
We've seen most of the code already, except the break
statement:
PHPif ($i == 5) {
break;
}
Simply put, as soon as the value of $i
reaches 5, we asked to break out of the loop and terminate it. That is why the last number echoed was 5.
Continue
The continue keyword is used whenever you want to skip ahead to the next iteration of the loop immediately, instead of finishing the rest of the code block.
Let's say in our previous example you didn't want to echo out any multiples of 3:
PHP<?php
$i = 0;
while ($i < 10) {
$i++;
if ($i % 3 == 0) {
continue;
}
echo($i . ' ');
}
?>
HTML1 2 4 5 7 8 10
Every time the value of $i
was a multiple of 3, we are using the continue statement before the echo so it is never shown:
PHPif ($i % 3 == 0) {
continue;
}
echo($i . ' ');
As you've seen, loops are extremely useful for making the same code block repeat over and over again in a compact and readable fashion.
- Getting Started with Solid
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- Getting Started with Sass
- Learn how to use v-model with a custom Vue component
- Using Puppeteer and Jest for End-to-End Testing
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Using Push.js to Display Web Browser Notifications
- Building a Real-Time Note-Taking App with Vue and Firebase