This tutorial follows the one on conditional statements. The loops are a trivial principle of computing that any developer must master. They are, too, some of the control structures. PHP 4 into account, each with its specific characteristics: for (), while (), do-while () and foreach ().
We’ll be covering the following topics in this tutorial:
What is a loop?
The term “loop” control structure capable of performing a number of times the same set of instructions as a function of one or more conditions to be checked.
It will always check conditions become false (FALSE) at some point in order to get out of the loop. Otherwise, the loop will become infinite and will crash the program until the max_execution_time php.ini will not be achieved.
The for loop ()
This is the most famous loops because it is present in most programming languages. Paradoxically, it is not necessarily the most used PHP programming. What for ? In most programming languages, the for statement () is used to browse a table, whereas PHP has its own control foreach () statement specifically dedicated to this task.
The peculiarity of the loop () (translate “for each iteration”) is that we must know in advance the stop condition. In other words, the value that will make the false condition and will stop the loop. Its syntax is simple and takes three mandatory parameters:
Syntax for () loop
for (initialization; condition; increment) { instruction block; }
• Initialization is the expression that initializes the loop (starting value). Generally, loops begin at 0.
• The second parameter is the stop condition of the loop. This condition is recalculated at each iteration (feedback loop) to determine if we continue to buckle or if one leaves the loop.
• The last parameter determines the phrase that will be executed at the end of an iteration. Generally it is expected here an increment (or decrement) to update the counter of the loop.
The following example shows the generation of the multiplication table of 9.
Generation number of multiplication table 9 with for ()
<?php // Loop generating the multiplication table of 9 for ($i = 0; $i <= 10; $i ++) { echo '9 x ', $i, ' = ', (9 * $i) ,'<br />'; } ?>
Explanations:
• We initialize our loop to 0. This is the first value that will be multiplied in number 9.
• We stop the loop when the $i counter reaches the value 11. The value 10 but when will i be worth $11 then the program will exit the loop.
• We determine the action to take at the end of each iteration. Here are asked to automatically increment the counter $i in writing $i++ ; (Reminder: $i++ <=> $i = $i+1).
• We display 10 values of the multiplication table of 9. The program calculates each value as the product of $9 by the counter i.
Note: the variable $i is completely arbitrary. This letter is used by convention (for i index) but nothing prevents write $ counter example.
The loop while ()
The while loop () means that we will repeat a block of statements as long as the last setting condition remains true (TRUE). When it becomes false (FALSE), the program will exit the loop.Its syntax shown below:
Syntax of the conditional structure while ()
while (condition) { instruction block; }
It is used particularly when the extracted information in a database. The peculiarity of this statement is that the condition is tested after the complete execution of the statement block. If the condition becomes false before the end, the remaining instructions will still be executed. Returning to our previous example, but this time with a while () loop.
Generation number of multiplication table 9 with while ()
<?php // Declaration and initialization counter $i = 0; // Loop generating the multiplication table of 9 while ($i <= 10) { // Display the new line echo ' 9 x ', $i, ' = ', (9 * $i) , '<br />'; // Increment the counter $i ++; } ?>
Explanations:
• Unlike the for () loop, we need to declare and initialize our counter before entering the loop. The default value is the same, ie 0.
• Then we determine the stop condition. When i will be worth $ 11 we will come out of the loop. The conditon $i <= $ 10 is always true as $ i is less than the value 11.
• Finally in the body of the loop, we calculate, and print the product of $ 9 by the counter i before finishing with a counter increment.
The do loop {…} while ()
The statement do {…} while () (translated as “repeat / do … as” an alternative to the while statement () that tests the condition after the first iteration and execution of the first block of . Here are instructions syntax:
Syntax of the control structures do – while ()
do { instruction block; } while (condition);
With our example, this would give:
Generation number of multiplication table 9 with do – while ()
<?php // Declaration and initialization counter $i = 0; // Loop generating the multiplication table of 9 do { // Display the new line echo '9 x ', $i, ' = ', (9 * $i), '<br />'; // Increment the counter $i ++; } while ($i <= 10); ?>
Explanations:
• We begin by initializing the counter to 0.
• Then we define the instruction list to run. Ie, computing, product display and incrementing the counter.
• We conclude with the test provided for out of the loop or not.
Note: If we had initialized the $ i counter to a value strictly greater than 10 (11, 12, 13 …), then the program would have calculated and displayed by the product of this value and 9 would be out of the loop because the condition is false at the beginning.
The foreach loop
In most programming languages, the route table is realized using loops. PHP has in turn its own control structure for browsing the contents of a table. This is the foreach () structure. It is a special loop which advances pointer table each iteration. It has been integrated since version 4 of PHP and comes in two syntaxes:
Syntax foreach control structure ()
<?php // Display the values of an array foreach ($MyArray as $value) { echo $value, '<br />'; }
// Display the key / value pairs
foreach ($MyArray as $key => $value)
{
echo $key, ‘:’, $value, ‘<br />’;
}
?>
This structure takes as parameter the name of the table to go and retrieve the data you need (only values or + key values). In the first syntax, the value of the
current element of the array is directly assigned to the variable $ value. In the second, the current key of the array element is assigned to the variable $key
and value stored in the variable $ value.
Note: foreach () works on a copy of the original array.
Consider two tables of example. The numerically indexed and the other associatively. We’ll go through them both with two foreach () statements in a different syntax.
Course tables with foreach ()
<?php // Declare the two tables $vegetables = array ('salad', 'onion', 'chilli', 'carrot', 'egg'); $colors = array ('red' => '#ff0000', 'green' => '#00ff00', 'blue' => '#0000ff');
// Display vegetables
foreach ($vegetables as $vegetable)
{
echo $vegetable, ‘<br />’;
}
// Display the colors and their hex code
foreach ($colors as $color => $codeHexadecimal)
{
echo $color, ‘:’, $codeHexadecimal, ‘<br />’;
}
?>
The stop instruction and continuity
PHP also introduced two special instructions loops. It is a continuous and break. The first is used to force the passage to the next iteration by jumping all or part of the block of instructions to execute. The second, meanwhile, can force out a conditional structure such as for(), while(), foreach() or switch().
These two instructions can take an optional integer parameter to know the number of nested structures that were interrupted.
Briefly illustrate these concepts with simple examples.
Example of continuous use
<?php for ($i = 0; $i <= 10; $i ++) { // It does not display the first 5 numbers if ($i <= 5) { continue; } // Display the numbers from June to October echo $i, '<br />'; } ?>
In this example, we want to iterate from the start value 0 but we want to show that values ranging from 6 to 10. With the condition and continues keyword, we can not view the first 6 values.
Note: we could achieve the same result without using the keyword continues by replacing the condition of the if () for $i> 5 and placing the echo () statement instead of continuing.
Easy-to-break
<?php for ($i = 0; $i <= 10; $i ++) { // It displays the counter value echo 'Counter = '; // We go out of the loop if we reached the figure 5 if ($i> 5) { break; } // Display the numbers 0-5 echo $i , '<br />'; } ?>
This example illustrates the use of the break keyword. Here we ask to exit the loop as soon as we reached the figure 5. To convince us of the result is the result generated:
Result of the script
Counter = 0
Counter = 1
Counter = 2
Counter = 3
Counter = 4
Counter = 5
Counter =
We note here that we entered the seventh iteration. The program executes the first instruction and then pass the test. The condition is true then the break