PHP while loop
The while
is a control flow statement that allows code to be executed repeatedly based on a given boolean condition.
This is the general form of the while
loop:
while (expression): statement
The while
loop executes the statement when the expression is evaluated to true. The statement is a simple statement terminated by a semicolon or a compound statement enclosed in curly brackets.
whilestm.php
<?php $i = 0; while ($i < 5) { echo "PHP language\n"; $i++; } ?>
In the code example, we repeatedly print “PHP language” string to the console.
The while
loop has three parts: initialization, testing, and updating. Each execution of the statement is called a cycle.
$i = 0;
We initiate the $i
variable. It is used as a counter in our script.
while ($i < 5) { ... }
The expression inside the square brackets is the second phase, the testing. The while loop executes the statements in the body until the expression is evaluated to false.
$i++;
The last, third phase of the while
loop is the updating; a counter is incremented. Note that improper handling of the while
loop may lead to endless cycles.
$ php whilestm.php PHP language PHP language PHP language PHP language PHP language
The program prints a message five times to the console.
The do while
loop is a version of the while
loop. The difference is that this version is guaranteed to run at least once.
dowhile.php
<?php $count = 0; do { echo "$count\n"; } while ($count != 0)
First the iteration is executed and then the truth expression is evaluated.
The while
loop is often used with the list()
and each()
functions.
seasons.php
<?php $seasons = ["Spring", "Summer", "Autumn", "Winter"]; while (list($idx , $val) = each($seasons)) { echo "$val\n"; } ?>
We have four seasons in a $seasons
array. We go through all the values and print them to the console. The each()
function returns the current key and value pair from an array and advances the array cursor. When the function reaches the end of the array, it returns false and the loop is terminated. The each()
function returns an array. There must be an array on the left side of the assignment too. We use the list()
function to create an array from two variables.
$ php seasons.php Spring Summer Autumn Winter
This is the output of the seasons.php
script.
PHP for keyword
The for
loop does the same thing as the while
loop. Only it puts all three phases, initialization, testing and updating into one place, between the round brackets. It is mainly used when the number of iteration is know before entering the loop.
Let’s have an example with the for
loop.
forloop.php
<?php $days = [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" ]; $len = count($days); for ($i = 0; $i < $len; $i++) { echo $days[$i], "\n"; } ?>
We have an array of days of a week. We want to print all these days from this array.
$len = count($days);
Or we can programmatically figure out the number of items in an array.
for ($i = 0; $i < $len; $i++) { echo $days[$i], "\n"; }
Here we have the for
loop construct. The three phases are divided by semicolons. First, the $i
counter is initiated. The initiation part takes place only once. Next, the test is conducted. If the result of the test is true, the statement is executed. Finally, the counter is incremented. This is one cycle. The for
loop iterates until the test expression is false.
$ php forloop.php Monday Tuesday Wednesday Thursday Friday Saturday Sunday
This is the output of the forloop.php
script.
PHP foreach statement
The foreach
construct simplifies traversing over collections of data. It has no explicit counter. The foreach
statement goes through the array one by one and the current value is copied to a variable defined in the construct. In PHP, we can use it to traverse over an array.
foreachstm.php
<?php $planets = [ "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" ]; foreach ($planets as $item) { echo "$item "; } echo "\n"; ?>
In this example, we use the foreach
statement to go through an array of planets.
foreach ($planets as $item) { echo "$item "; }
The usage of the foreach
statement is straightforward. The $planets
is the array that we iterate through. The $item
is the temporary variable that has the current value from the array. The foreach
statement goes through all the planets and prints them to the console.
$ php foreachstm.php Mercury Venus Earth Mars Jupiter Saturn Uranus Neptune
Running the above PHP script gives this output.
There is another syntax of the foreach
statement. It is used with maps.
foreachstm2.php
<?php $benelux = [ 'be' => 'Belgium', 'lu' => 'Luxembourgh', 'nl' => 'Netherlands' ]; foreach ($benelux as $key => $value) { echo "$key is $value\n"; } ?>
In our script, we have a $benelux
map. It contains domain names mapped to the benelux states. We traverse the array and print both keys and their values to the console.
$ php foreachstm2.php be is Belgium lu is Luxembourgh nl is Netherlands
This is the outcome of the script.
PHP break, continue statements
The break
statement is used to terminate the loop. The continue
statement is used to skip a part of the loop and continue with the next iteration of the loop.
testbreak.php
<?php while (true) { $val = rand(1, 30); echo $val, " "; if ($val == 22) break; } echo "\n"; ?>
We define an endless while
loop. There is only one way to jump out of a such loop—using the break
statement. We choose a random value from 1 to 30 and print it. If the value equals to 22, we finish the endless while loop.
$ php testbreak.php 6 11 13 5 5 21 9 1 21 22
We might get something like this.
In the following example, we print a list of numbers that cannot be divided by 2 without a remainder.
testcontinue.php
<?php $num = 0; while ($num < 1000) { $num++; if (($num % 2) == 0) continue; echo "$num "; } echo "\n"; ?>
We iterate through numbers 1..999 with the while
loop.
if (($num % 2) == 0) continue;
If the expression $num % 2
returns 0, the number in question can be divided by 2. The continue
statement is executed and the rest of the cycle is skipped. In our case, the last statement of the loop is skipped and the number is not printed to the console. The next iteration is started.