Loops in PHP are very useful when you need to perform repetitions of the same code over and over again, or when you need to ensure that you iterate through all possible values of an array, for example. They come in a few different flavours, the most common being “for” loops and “while” loops. There are a few other more obscure ways to create loops, and I’ll cover them at the end, in the extended section.
The three types of loop I will cover in this section are For loops, While loops and Foreach loops
While loops are the simplest kind of loop in PHP. They’re pretty much just saying “Do something for a while until a certain condition is satisfied”. You could be saying Stay at work until this project is finished or Keep on running this marathon until you get to the end
The general syntax of a while loop is as follows
while(condition = true) {
do something
}A real-world code example of this might be
1 2 3 4 5 6 7 8 | $miles_completed = 0; $race_finished = false; while($race_finished == false) { $miles_completed++; if($miles_completed >= 26){ $race_finished = true; } } |
I’ll explain some of the symbols and operations going on here…
- Lines 1 and 2 : we initialise the values of $miles_completed and $race_finished. The code wouldn’t work properly otherwise, as $race_completed has to be equal to FALSE initially to satisfy the while loop in line 3
- Line 3 : The while loop will repeat as long as $race_finished is equal to false. A drawback of while loops is that they can loop indefinitely if you are not careful, and this will cause your application to crash - you can see how this would occur if we didn’t increment the value of $miles_completed or set $race_completed to be true. You’d be running that marathon for ever!
- Line 4 : the expression $miles_completed++; is a way of saying $miles_completed = $miles_completed+1; This can also be rewritten as $miles_completed += 1;
- Line 5 : we check the value of $miles_completed on every repetition of the loop. Once $miles_completed becomes greater than 10 (since we are incrementing the value every time round) then $rage_finished is set to TRUE, therefore breaking the condition that keeps the loop going
Another way of writing while loops is to invoke the “do” statement
$miles_completed = 0; $race_finished = false; do { $miles_completed++; if($miles_completed >= 26){ $race_finished = true; } } while($race_finished == false);
The only difference here is that the statement between do.. and ..while will always be executed at least once before the loop begins. So, for example, the code
$line = "Texty texty text text"; $a = 1; do { echo $line; } while($a == 2);
will output
Texty texty text text
even though the condition of the while loop (that a must equal 2) is false
For loops are probably the most common type of loop found in PHP, and indeed in most other kinds of programming language. They can be used to loop through a series of repetitions like a while loop, but with some advantages. It’s not so easy to create a for loop that will never end, since the code to define the “exit condition” as well as the code to increment the count for the loop are defined explicitly at the start
The syntax of for-loops is as follows
for(loop initialisation code; the loop "exit condition"; code to evaluate before each loop){
//the code to execute on each loop goes in here
}A more concrete example of the for loop, and the most commonly encountered style is
for($i = 0; $i < 100; $i++){ echo "i = $i"; }
- $i = 0 : This sets up the variable $i for the purpose of the loop. In this instance, we’re going to continually check the value of $i after every loop, and only exit when the second element evaluates to true…
- $i < 100 : Since we initially set $i = 0, then this statement will initially evaluate to false. The loop will exit only after this condition becomes true, which is the task of the final element…
- $i++ : This statement says that we want to increment the value of $i after every loop. After 100 loops, $i will be greater than 100, so the loop will exit successfully
This for loop will produce the output
i = 0 i = 1 i = 2 (... and so on)
Some other examples of for loops, using slightly different code
for($i = 50; $i>0; $i--) /* same as before, but decreasing $i */ for($i = 0; $i < 100; $i+=2) /* increase $i by 2 every time */ for($i = "Hello"; strlen($i)>0; $i=substr($i, 0 ,strlen($i)-1)){ echo $i; } // this prints out... // Hello // Hell // Hel // He // H
Foreach loops are a particularly useful feature of PHP when working with arrays as they allow us to iterate through all the values of an array in sequence. Foreach loops also allow us to access the keys of an array, which is a useful feature when working with associative arrays.
An example of the foreach syntax is
/* three people, and their respective scores in a test*/ $scores = array("jeff" => 74, "bill" => 88, "john" => 63); foreach($scores as $value){ echo $value; }
The “as” keyword is used to assign each value in the array to a temporary variable for use within the loop. Inside the loop, operations can be carried out on each value in turn. The above code will output
74 88 63
If we wish to perform operations on keys as well as values, we can make a slight adjustment to the syntax
$scores = array("jeff" => 74, "bill" => 88, "john" => 63); foreach($scores as $key => $value){ echo "$key, $value"; }
The operator => is used to let PHP know that we want to assign a temporary variable to each key in the array as well as each value. In the case of an indexed array, where we haven’t explicitly defined the keys, each key will simply be an incremental numerical value - 0, 1, 2 etc.
jeff, 74 bill, 88 john, 63
When performing operations on an array, it’s often useful to be able to modify the contents of the array in some way. Here, we might want to replace each score with a “pass” or “fail” depending on whether the score is above the pass mark (let’s say 70 in this case)
We can make use of the “pass by reference” functionality of PHP to state that the temporary variable $value shouldn’t be assigned the actual value of each array element, but instead should point directly to that array element, like so
1 2 3 4 5 6 7 8 9 | $scores = array("jeff" => 74, "bill" => 88, "john" => 63); foreach($scores as &$value){ if($value >= 70) $value = "pass"; else $value = "fail"; } unset($value); print_r($scores); |
This will give us
Array ( [jeff] => pass [bill] => pass [john] => fail )
Notice in line 8 of the above code, we use the statement unset($value). This is because, after iterating through an array passed by reference in this way, references to the final element of the array, and to $value still remain, so it’s good practice to destroy them via the use of the unset() function.



