Welcome to this discussion of PHP loops: what loops are, whey they’re important, and how to use PHP while()
loops. This article continues our series explaining the basics of PHP for WordPress development.
Our deep-dive into loops builds on topics we’ve covered in earlier articles, especially the concept of control flow: the logic of “what happens when,” in both PHP and all other imperative programming languages. Loops are a subtopic within control flow: they’re all about “what happens when,” and specifically about how many times it happens.
Why Loops Matter in PHP
A common need in programming is to repeat a similar action multiple times.
In programming, as in life, an extremely common need is to do a similar thing over and over again.
In life, this might be “for each dish in the sink: soap, scrub, and rinse the dish, then put it in the drying rack, continuing until the sink is empty.” Or literally zillions of other examples.
In programming, this might be “for each user in the WordPress database: retrieve that user’s username, continuing until all usernames have been retrieved.” Or literally zillions of other examples.
To code these sorts of repeated tasks in PHP, loops are pretty much the only game in town. Let’s give a quick example.
Why We Need Loops: A Simple Example
Consider the following need: “I want to write a function that prints out integers in sequence, beginning with 0 and going up to any number.”
How would we code this? Let’s first try it without loops:
<?php
// Okay, let's try this without loops...
function count_up_from_zero( $top_number ) {
// If the top number is 0, that's easy
if( $top_number === 0 ) :
echo '0 '; // Will print out "0 "
// Or maybe it's 1
elseif( $top_number === 1 ) :
echo '0 1 '; // Will print out "0 1 "
// Or the top number could be 2
elseif( $top_number === 2 ) :
echo '0 1 2 '; // Will print out "0 1 2 "
// Of course, the top number could also be 3...
elseif( $top_number === 2 ) :
echo '0 1 2 3 '; // Will print out "0 1 2 3 "
// ...or... 4...
elseif( $top_number === 4 ) :
echo '0 1 2 3 4 '; // Will print out "0 1 2 3 4 "
// ...wait, does this function have to go on forever?...
endif;
}
Okay, time to use loops:
<?php
// Hey guys I just learned about loops
function count_up_from_zero( $top_number ) {
$i = 0;
// The operator <= means "is less than or equal to"
while( $i <= $top_number ) :
echo $i . ' '; // Will print whatever $i is plus " "
$i++; // This means "increase $i by 1"
endwhile;
}
count_up_from_zero( 6 ); // Will print out "0 1 2 3 4 5 6 "
As this example shows, if you want to be able to write PHP code that repeats something an unknown number of times, you’ll need loops.
More generally, once you really get into coding—in WordPress or any other PHP software—loops are absolutely everywhere. Let’s take a closer look at how loops function in PHP, looking first, in this article, at PHP while()
loops, and covering foreach()
loops in a separate article.
What about for()
and do...while
Loops?
As I mentioned in the article on control flow, I’ve never found a need for a for()
loop—at least in WordPress—that I couldn’t refactor more simply into a while()
loop. So I encourage you to learn for()
loop syntax, but I won’t be covering it here. Similarly, I just learned today that PHP even has a do...while
syntax, so probably safe to skip that one.
PHP while()
Loops: How and Why to Use Them
How a while()
Loop Thinks
The crucial part of a while()
loop is the bit inside while()
itself. What does that code do, and how does a PHP while()
loop work more broadly?
while()
will repeat as long as the condition inside it remains true.
A while()
loop will run over and over again (it will loop) as long as (while) the condition that’s inside it remains true.
Let’s look at some examples to see how this works in practice:
<?php
// false is not equal to true, so this loop won't run even once
while( false === true ) :
echo 'Hi'; // This code will never run
endwhile;
// false is always not true, so this loop will never run
// This code is equivalent to the example above
while( false ) :
echo 'Hi'; // This code will never run
endwhile;
// true is always true: this loop will run forever, until PHP crashes
while( true ) :
echo 'lo'; // Will print out "lolololololol" until PHP crashes
endwhile;
// Now we're getting somewhere: this loop will run 10 times
// and will print out "0123456789"
$i = 0;
while( $i < 10 ) :
echo $i; // Will print whatever $i is equal to
$i++; // This means "grow $i by 1"
endwhile;
Each one of the four examples above is a valid while()
loop in PHP. However, the only actually useful one is the fourth, which both runs (unlike the first two) and stops (unlike the third).
Let’s look more at how that fourth while()
loop example works, in terms of its control flow sequence:
- First,
$i
is set to 0. - The
while()
loop asks: “Is$i
less than 10?” Yes, it is (it’s 0), so the code inside the loop runs. - Inside the loop, the
echo $i;
command prints out “0” into the HTML document. - Inside the loop, the
$i++;
command adds 1 to$i
.$i
is now equal to 1. - The loop is finished, so it loops around back to the top, and asks again: “Is
$i
less than 10?” Yes, it is (it’s 1), so the code inside the loop runs. - This prints “1” to the page and increases
$i
by 1, so that$i
now equals 2. - This process continues through 2, 3, 4, 5, 6, 7, and 8, until
$i
is equal to 9 and we’ve printed “9” to the page. Now it’s time to add 1 to$i
. That makes$i
equal to 10. - Now we loop back around to the top again, and ask: “Is
$i
less than 10?” No, it isn’t (it’s 10), so the loop stops executing. PHP would then move onto the next piece of code on the page.
This is how the fourth loop, above, causes PHP to print out “0123456789” and then move onto the next thing—a simple, working while()
loop.
Iterators and $i
As you saw in the code above, a variable $i
is very important to the functioning of some while()
loops. What’s up with that?
A
while()
loop will often use an iterator: a variable that counts “how many times” you’ve done something.
The variable $i
was an iterator: a variable that exists to count “how many times” you’ve done something. It’s like counting laps, and clicking a stopwatch on each lap: each click of the stopwatch is equivalent to increasing $i
by one with $i++;
.
Do our iterators have to be named $i
? Not for any technical reason, no: this is just convention. You could name your iterator $metallicasearlyworkwassuperior
if you’ve got the finger speed to be writing out $metallicasearlyworkwassuperior++;
under your loops.
But if you follow convention by naming your iterators $i
(or $j
or $k
if you happen to need multiple iterators at once, which is fairly rare, at least in WordPress), other programmers will understand what you’re trying to do. So we recommend that.
<?php
$fruits = [ 'apple', 'banana', 'mango' ];
echo $fruits[0]; // Will print "apple"
echo $fruits[1] // Will print "banana"
echo $fruits[2] // Will print "mango"
echo $fruits[3] // Nope!
So we generally want o
Learning to Count from 0
For reasons that are very beautiful and also fairly technical, most programming languages—PHP included—start counting not from 1 but from 0. For example, PHP arrays start from index 0:
<?php
$fruits = [ 'apple', 'banana', 'mango' ];
echo $fruits[0]; // Will print "apple"
echo $fruits[1] // Will print "banana"
echo $fruits[2] // Will print "mango"
echo $fruits[3] // Nope!
So we generally want our iterators to start from 0 as well:
<?php
// This loop will run 100 times
$i = 0;
while( $i < 100 ) :
$i++;
endwhile;
// This loop will run 100 times too, but don't do it this way:
// It's not how programming languages think
$i = 1;
while( $i <= 100 ) :
$i++;
endwhile;
}
// Here's another example to show why to start counting from 0
$fruits = [ 'apple', 'banana', 'mango' ];
// This loop will print out "apple banana mango "
$i = 0;
// count() gives you the number of $fruits array elements, which is 3
while( $i < count( $fruits ) ) :
echo $fruits[$i] . ' ';
endwhile;
// This loop will print out "banana mango "
// You skipped the first array element,
// probably not what you intended
$i = 1;
while( $i < count( $fruits ) ) :
echo $fruits[$i] . ' ';
endwhile;
}
count_up_from_zero( 6 ); // Will print out "0 1 2 3 4 5 6 "
You should find ways to start your
$i
iterator at 0, with few exceptions.
In sum: You should find ways to start your $i
iterator at 0, with few exceptions.
Using the break
Statement in while()
Loops
So far, we’ve seen while()
loops that run until their natural conclusion—that is, until the condition listed inside the while()
statement itself is no longer true.
There’s another way to end a while()
loop—or any other loop you’re running in PHP. It’s the break
statement.
Here’s an example. It’s actually a fully-functioning game of chance, using PHP’s rand()
function, which generates random numbers:
<?php
$target_number = rand( 1, 6 ); // $target_number is now a random integer from 1 to 6
$my_roll = rand( 1, 6 ); // $my_roll is now a random integer from 1 to 6
echo 'Target roll is ' . $target_number . '. ';
$rolls_needed_to_win = 0; // Let's count how many rolls it takes us to roll our target
// while( true ) will run until we hit our break statement
while( true ) :
echo 'Rolled a ' . $my_roll . '. ';
$rolls_needed_to_win++; // We just rolled, add 1 to our count of rolls
// Break from the loop if our roll equals the target roll
if( $my_roll === $target_number ) :
echo ' Winner!!! ';
break; // This is our way to exit the loop
endif;
// Our roll didn't equal the target roll, so roll again and loop around
$my_roll = rand( 1, 6 ); // $my_roll is again set to be a random integer from 1 to 6
endwhile;
// After we win, print out information
echo 'You needed ' . $rolls_needed_to_win . ' tries to roll your target of ' . $target_number . '.';
As you can see, break
will exit a loop “early,” once the condition that the loop is designed for (here, making a matching roll) is satisfied. After break
causes it to exit the loop, PHP will continue to execute, so the line after the endwhile
will be next in line for execution.
Note that our use of while( true )
with a break is, arguably, slightly ugly code. This is why some programmers recommend do...while
, but again, let’s not get into that.
while()
Loops Without Iterators
As we’ve seen, for a while()
loop to be useful—and not break your site—it needs two properties:
- It needs to be able to run under some circumstances. Looping “while” something that is always false is wasted code.
- Once it does run, it should never loop infinitely.
In many examples, we’ve used $i
iterators for this, but our previous example with rand()
shows that it’s quite possible to write while()
loops that don’t use iterators, as long as they satisfy the two conditions above.
In our rand()
example, we had a counter, $rolls_needed_to_win
, but that counter played no part in determining how many times the loop would execute. Instead, we used an if()
-statement, with a break
inside, to control execution.
WordPress Connection: The Loop
Our discussion of while()
loops—especially those without iterators—could not be more relevant to WordPress’s code. All WordPress themes are built around a specific while()
loop, which is so central to WordPress’s functioning that it’s simply called “The Loop.”
Armed with your understanding of while()
loops in general, we heartily recommend that you learn how The Loop functions. It should make a ton of sense to you, and should turn on a lot of lights about how WordPress actually displays your posts.
See You in a while()
You should now understand the “do something multiple times” nature of loops, one of the most common constructs in all of programming. You should also have a great sense of how PHP’s while()
loops work, how to use them with and without iterators, and how WordPress uses while()
loops—and particularly The Loop—for its core functioning.
Thanks for reading! We’d love to hear any questions or thoughts, either in the comments below or in our Facebook group.