PHP for, foreach, while, do-while Loops

PHP, like most programming languages, offers several options for iterating or “looping” through arrays.  Looping isn’t limited to just arrays.  A loop can traverse any object of an iterable type.  This means we can iterate through objects and access it’s properties as key/value pairs the same way we can with arrays.

More still, loops are not restricted to just traversing arrays or objects.  They can also be used to run blocks of code when or until certain conditions are met.  We’ll cover the basic types of loops here.

Jump to:

Skipping iterations and breaking loops

All the loop structures feature the ability to break out of the loop or continue to the next iteration.  We will see the usage of these statements in the some of the examples below.  Let’s dive into the different types of loops in PHP.

 

 

The for loop

The for loop is described as the most complex loop in PHP.  While this can be true, the average use of the for loop can be pretty basic.  The for loop accepts three expressions.  The first is executed once at the beginning.  The second expression is used to define the conditions which much be met to continue executing the loop code block.  The third expression is executed after each iteration of the loop.

A common use of the for loop is to execute a block of code for every number between a min and max value.  Lets count from 1 to 10 using a for loop:

for($i = 1; $i <= 10; $i++;) {
    echo $i."\n";
}

The three expressions we’re using in the loop can be broken down like this:

$i = 1; Starts our structure by creating a variable $i and setting it’s value to 1.
$i <= 10; Allows us to continue executing our code block as long as the value of $i is less than or equal to 10.
$i++; Increments the value of $i after each iteration of the loop.

The above code will output:

1
2
3
4
5
6
7
8
9
10

Lets see an example of a for loop used to iterate through an array:

$array = ['hello', 'world'];
$arraySize = count($array);
for($i = 0; $i < $arraySize; $i++) {
    echo $array[$i]." ";
}

We created an array of words hello and world.  Our for loop iterates through the array and outputs each word from the $array.  The output will be:

hello world

 

The foreach loop

The foreach construct provides an easy way to iterate through an array or an iterable object.  It allows us to execute a block of code for every element in the iterable.   The foreach loop accepts an array or iterable object and either a value or key/value representation of the element.  We use the as keyword to assign each element to a variable we can use in the loop code.

As seen above, a for loop can be used to iterate an array, but requires that we calculate the size first to create our conditional expression.  The foreach loop is a simpler syntax and doesn’t require the size of the iterable to be in a condition.  Let’s use the same example above, but with a foreach loop instead:

$array = ['hello', 'world'];
foreach($array as $word) {
    echo $word." ";
}

This example will output the same hello world as the for loop.  However, the code is a bit less verbose.  Our hello world example iterates through our $array and assigns each element to the $word variable used in our code block.  What if we want to use the same $array above, but also output the array key for each element?  We can adjust our foreach loop like this:

$array = ['hello', 'world'];
foreach($array as $idx => $word) {
    echo $idx.': '.$word."\n";
}

This will iterate through our $array and output each element key and value:

0: hello
1: world

We can also use a foreach loop to modify the original array elements.  We can use & in front of our as value variable to reference the original array element instead of working with a cloned value.  If we want to take our array and make each word uppercase, we have two options.  We can either create a new array to hold the uppercase values, or use the & indicator to modify the original array values.

Option #1 – New array with uppercase words:

$array = ['hello', 'world'];
$uppercaseWords = [];
foreach($array as $word) {
    $uppercaseWords[] = strtoupper($word);
}

echo print_r($uppercaseWords, true);

Option #2 – Modify original array:

$array = ['hello', 'world'];
foreach($array as &$word) {
    $word = strtoupper($word);
}

echo print_r($array, true);

Both options will have the same output (an array of uppercase words).

Array
(
    [0] => HELLO
    [1] => WORLD
)

 

The while loop

The while loop is described as the simplest PHP loop.  It accepts an expression in the definition.  It will evaluate the expression and if the result is true, it will execute the loop code.  If the result is false, the loop code will not be executed further.  We can use a while loop to count to 10 as we did in the for loop above.  This would look like:

$i = 1;
while($i <= 10) {
    echo $i."\n";
    $i++;
}

The while loop checks the value of $i.  If it’s current value is less than or equal to 10, it will execute the code in our loop block.  The last line of our while loop $i++; increments the value of $i, then the loop checks again and continues to iterate as long as the condition remains true.  The above code will output:

1
2
3
4
5
6
7
8
9
10

Warning:  if we don’t include the $i++; line above, it will execute an infinite loop and could end up crashing our system.  We must always be sure we have a way to break the loop.  The above example uses our conditional expression to break the loop as soon as $i is greater than 10.  Another way to stop the loop is to use break from inside our code block.  We can use the same counting example above with a break instead of defining our condition in the expression:

$i = 1;
while(true) {
    if($i > 10) break;
    echo $i."\n";
    $i++;
}

Using while(true) will never result in a false value.  So our it will basically loop forever until we manually stop it using break.  As previously mentioned, be sure to avoid infinite loops by making sure your code has a way out of the iteration.

Let’s create an example of using continue to “skip” iterations without completely abandoning the loop.  We’ll adjust our example count to 100 in increments of 10:

$i = 0;
while($i <= 100) {
    $i++;
    if($i % 10 !== 0) continue;
    echo $i."\n";
}

This will output:

10
20
30
40
50
60
70
80
90
100

There are certainly better ways of counting to 100 by tens.  But this lets us try out continue in a while loop to accomplish it.

 

The do-while loop

The do-while loop is basically the same as the while loop except the conditional expression is evaluated after the code block.  This means that it will run our do loop code first, then check to see if the expression in while results in true or false.  If the result is true it will execute our do code again, if not, the loop is broken.  Let’s build our counter using a do-while loop:

$i = 1;
do {
    echo $i."\n";
    $i++;
}
while($i <= 10);

This will give us the same 1 through 10 count as seen in the other loops.  Let’s see an example that illustrates the difference in execution between while and do-while loops:

$whileCounter = 0;
while(false) {
    $whileCounter++;
}
echo 'while iteration count: '.$whileCounter."\n";

$doWhileCounter = 0;
do {
    $doWhileCounter++;
}
while(false);
echo 'do-while iteration count: '.$doWhileCounter."\n";

The output is:

while iteration count: 0
do-while iteration count: 1

The while loop code is executed zero times, because while(false) is checked first and never results in true, so our counter is never incremented.  Conversely, our do-while loop code is executed exactly once even though we have the same expression that will never equal true.  Since it’s a do-while loop, the code is executed first, then the expression is evaluated to see if the loop should continue.

 

Wrap it up

Loops are one of the basic building blocks of any programming language.  There are different types of loops offered in PHP.  Sometimes it is a matter of preference when deciding when to use one loop over another.  Sometimes there is a better loop for a specific task.  The basics of each loop type described here should give a basic understanding of each type and help determine how/when to use each type.

Enjoy!

Leave a Reply

avatar
  Subscribe  
Notify of