Loops are an important part of almost every programming language.
They allow us to repeatedly execute blocks of code until some
kind of exit or break condition occurs.
They can be used for reading files line by line, traversing through
arrays (lists of data), benchmarking and more.
- The for Loop
- The foreach Loop
- The while Loop
- The do-while Loop
- Exit & skip loops with break & continue
The for Loop
The for loop is pretty straight forward. We set a start value $i = 1
used for counting followed by an expression $i <= 10
.
While the expression is evaluated as true, the code in the
body {}
is executed.
After that the counter is increased by 1 using the post-increment
operator which looks like so $i++
, before jumping back to the evaluation.
for ($i = 1; $i <= 5; $i++) {
echo "$i loop(s) executed\n";
}
echo "In the end, the value still goes to $i\n";
1 loop(s) executed
2 loop(s) executed
3 loop(s) executed
4 loop(s) executed
5 loop(s) executed
In the end, the value still goes to 6
The foreach Loop
Probably the most commonly used loop in PHP is the foreach
loop.
It is the easiest way to iterate through arrays and looks like so
foreach ($array as $value) { do something }
.
We're basically telling PHP to go step by step through our
array (list of values) and copy the value into a variable which we
can use in the body of our loop {}
. The variable name is up for us
to choose, but it's generally a good idea to use a $plural as $singular
notation.
Optionally we can also retrieve the key (the array index) of the value
by changing our loop like so foreach ($array as $key => $value) {}
.
This can be a little confusing at first, so make sure to play around
using different values with the example below.
$names = ['Bob', 'John', 'Harry', ];
foreach ($names as $key => $name) {
echo "$key: Hello $name\n";
}
0: Hello Bob
1: Hello John
2: Hello Harry
The while Loop
While loops, similar to for loops, allow us to execute a block of code,
while a given condition is true. Careful tough. Make sure that you
have a solid condition that will return false
at some point,
otherwise we would end up with a so-called infinite loop.
The basic structure of a while loop looks like an if statement
while (expression) { do something }
. The only difference is
the while
keyword, which tells PHP that we want to execute the
part in the body {}
not just once, but over and over again.
By the way, the -=
operator we're using to lower the $accountBalance is
the short version of $accountBalance = $accountBalance - $withdrawalAmount;
We could also do the opposite with the +=
operator.
$accountBalance = 100;
$withdrawalAmount = 20;
while ($accountBalance >= 20) {
$accountBalance -= $withdrawalAmount;
echo "withdrawing $withdrawalAmount bucks, $accountBalance remaining\n";
}
withdrawing 20 bucks, 80 remaining
withdrawing 20 bucks, 60 remaining
withdrawing 20 bucks, 40 remaining
withdrawing 20 bucks, 20 remaining
withdrawing 20 bucks, 0 remaining
The do-while Loop
The less popular brother of the while loop is the do-while loop.
What it basically does is reversing the order into
do { something } while (expression);
. Take note of the trailing
semicolon at the end.
A do-while loop allows us to execute the code between the curly braces at least once before it checks if the expression below returns true or not.
// play with different values
$accountBalance = 20;
do {
echo "Current account balance: $accountBalance\n";
$accountBalance += 5;
} while ($accountBalance < 20);
echo "Final account balance: $accountBalance\n";
Current account balance: 20
Final account balance: 25
As you can see, even though the condition of having an account balance less than 20 was not met, our code was still executed once.
Skipping or Stopping/Exiting a Loop prematurely
Sometimes we might run into a situation where we want to skip a
single iteration of a loop or even exit a loop altogether.
This is quite common when processing data.
To skip a single iteration we can use the keyword continue
and
to exit/end the loop we have the keyword break
.
foreach ($items as $item) {
if ($breakConditionIsMet) {
break; // exits the loop entirely
} elseif ($continueConditionIsMet) {
continue; // skips this iteration
}
}
It's really just that easy - break;
or continue;
is all that is needed.
In some cases we may want to break out of nested loops. To achieve this,
we can optionally write a number directly after.
foreach ($items as $item) {
foreach ($item as $value) {
break 2;
}
}
// after break 2, we end up right here, exiting both loops
previous : : Control Structures And Their Operatorsnext : : Using And Declaring Functions In Php