PHP FOR Loops: How to Use the FOR Loop in PHP
The PHP FOR loop is one of the most important functions in PHP programming. If you’ve ever written a FOR loop in JavaScript, C, or Python, it will look very similar. And once you know the basics of the PHP FOR loop, you’ll also be able to learn the FOR loop very easily in other languages.
What is a PHP FOR Loop?
The first thing you should know about the FOR loop is that it’s one of the most common PHP interview questions. Not only should you know the basics of FOR loops, but you should be practiced enough to program one on the fly.
Let’s start with the syntax of the FOR loop. If you’ve never seen a FOR loop before, this is going to appear overwhelming. But we will break it down into simple components.
for([starting_condition]; [continue_condition]; [ending_condition]) {
[code_block]
}
The above parameters of the FOR loop, as described, are:
- Starting condition. An expression of code that starts when the for loop is first initiated, but never again.
- Continue condition. A condition evaluated each time the loop runs. If this returns true, the execution continues. If this returns false, the execution stops.
- Ending condition. An expression of code that runs at the end of each loop.
- Code block. The code that runs as each loop iteration is completed.
Last Updated September 2024
PHP for Beginners: learn everything you need to become a professional PHP developer with practical exercises & projects. | By Edwin Diaz | 900,000+ Students, Coding Faculty Solutions
Explore CourseThe control structure of a FOR loop can initially be difficult to understand, but it’s a lot easier if you see an example:
for($i = 1; $i <= 10; $i++) {
echo "$i<br>";
}
The above code starts a counter ($i) at 1. It then checks to see if the counter is less than or equal to 10. If it’s less than or equal to 10, it prints the number and then performs a counter increment ($i++).
The end result of the code is a list of the numbers 1 through 10.
You control the number of times the loop repeats through the initial counter and the counter increment. As long as the middle condition evaluates to true, the loop executes.
Let’s look at another example:
$colors = array('Periwinkle','Cerulean','Slate');
for($i = 0; $i <= sizeof($colors); $i++) {
echo $colors[$i];
echo "<br>";
}
The above code creates and then loops through an array of colors. This is how you use FOR loops to loop through arrays. Here, the $i counter serves as a key to the array elements. You can also see that the “condition” expression can include something more complex, such as the SIZEOF function (which gets the size of the array).
Exiting a FOR loop with a BREAK statement
What if you want to exit a FOR loop early? The easiest way to exit a FOR loop (or any other loop) is the BREAK statement. Let’s take our earlier example:
for($i = 1; $i <= 10; $i++) {
echo "$i<br>";
if($i==7) {
break;
}
}
Now the loop never gets to 8, 9, or 10 because it breaks once the counter ($i) is set to 7. You can use a “break” to exit out of a loop if an error occurs, but the break statement should usually be used sparingly.
Top courses in PHP (programming language)
Alternatives to the FOR loop
The FOR loop is only one of many popular loop structures. We’re going to take a look at a few of the other popular types of loops: FOREACH loops, WHILE loops, and SWITCH statements.
FOR vs. FOREACH loops
The PHP FOREACH loop will loop through a PHP array or object. It’s specifically designed to do this. You can use the FOREACH loop as follows:
$colors = array('Periwinkle','Cerulean','Slate');
foreach($colors as $color) {
print($color . "<br>");
}
As you can see, the FOREACH loop is a lot simpler when an array is involved. Instead of having those three statements, you have a single statement. For each array item in the array “$colors,” that item will be referenced by the temporary value of “$color.”
FOR vs. WHILE loops
The PHP WHILE loop is another interesting loop. This loop only has a single condition. It will continue to loop until that condition is broken.
$c = 1;
while($c <= 10) {
print($c . "<br>");
$c++;
}
In the above example, you can see that a WHILE loop is sort of just a FOR loop with the syntax moved around. We need to set the counter manually above the loop. We test the condition in the WHILE() function parameters, and then we increment the counter within the code block.
FOR vs. SWITCH statements
SWITCH statements are another unique proposition. A SWITCH statement switches through a series of “cases.” The SWITCH statement syntax is as follows:
switch($case) {
case 0: [code_block]; break;
case 1: [code_block]; break;
case 2: [code_block]; break;
...
}
FOR and SWITCH functions are used entirely differently from each other, but they’re close enough that it’s important to know both — because you may run into situations in which one is better than the other.
Let’s look at an example of a SWITCH statement. We want to figure out where to eat, and we have four options. We generate a random number:
$random = rand(0,3);
switch($random) {
case 1: echo "Mexican!"; break;
case 2: echo "Italian!"; break;
case 3: echo "American!"; break;
default: echo "We have food at home!"; break;
}
This code prints out Mexican, American, or Italian for cases 1 through 3. For any other case (including 0), it prints out, “We have food at home!”
PHP (programming language) students also learn
Common mistakes with PHP FOR loops
Your FOR loop isn’t working. What happened? There are some common mistakes with PHP FOR loops that a lot of programmers will run into. Let’s start with the first problem — accidentally changing your counter.
for($c = 0; $c <= 10; $c++) {
$c=1;
print("$c<br>");
}
What happens when you try to run this code? An infamous thing called “infinite recursion.” This loop is never going to end because inside of the loop, you set $c to = 1. $c is never going to be more than or equal to 10, so the loop will never end.
It’s easy to see in this code, but in code that’s complex, it can be easy to accidentally change a variable. For instance, you might try to write “if $c == 0” and accidentally write “if $c = 0.”
This is one reason why most programmers use $i; they know that this is the counter variable and should not be touched.
Another common error is a fence post error:
$for($c = 1; $c < sizeof[$array]; $c++) {
print("$array[$c]<br>");
}
A fence post error is also known as an “off by one” error. It just means that you started counting either too late or too early. In this case, we did both. First, an array starts at 0, not 1. Second, we would need to count to “less than or equal to” not just “less than.” The above code would cut off both the beginning and the end of the array.
Always remember that computers start counting at 0, not 1.
Using the PHP FOR loop
You should now know everything there is to know about the PHP FOR loop; how to use it, when to use it, and what mistakes to avoid. You should even know a little bit about alternatives to using the FOR loop, such as WHILE, FOREACH, and SWITCH.
But that’s not all you need to know to become a better PHP programmer. Becoming a better PHP programmer takes practice and time. While you’re studying PHP, consider picking up some practice PHP projects, learning more about PHP functions, or taking some practice PHP interview questions.