How to PHP Scripting- Looping Statements
Looping Statements in PHP are used to execute the same block of code a specified number of times. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort.
In PHP, we have the following looping statements:
1.while – loops through a block of code as long as the specified condition is true
2.do…while – loops through a block of code once, and then repeats the loop as long as the specified condition is true
3.for – loops through a block of code a specified number of times
4.foreach – loops through a block of code for each element in an array.
1.while loop
The while statement will loop through a block of code until the condition in the while statement evaluates to true.
while (condition) { code to be executed; }
The example below define a loop that starts with $i=1. The loop will continue to run as long as $i is less than or equal to 4. The $i will increase by 1 each time the loop runs.
<?php $i = 1; while($i <= 4){ $i++; echo "The number is " . $i . "<br>"; } ?>
2.do…while loop
The do…while statement will execute a block of code at least once – it then will repeat the loop as long as a condition is true.
do { code to be exected; }while (condition);
The following example defines a loop that starts with $i=1. It will then increase $i with 1, and print the output. Then the condition is evaluated, and the loop will continue to run as long as $i is less than, or equal to 10.
<?php $i = 0; do { echo "The number is ".$i."<br/>"; $i++; } while ($i <= 10); ?>
3.for loop
The for statement is used when you know how many times you want to execute a statement or a block of statements.
for(initialization; condition; increment){ // Code to be executed }
The initialization is executed once unconditionally at the beginning of the loop.
In the beginning of each iteration, condition is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.
At the end of each iteration, increment is executed.
<?php for ($i=0; $i <= 10; $i++) { echo "The number is ".$i."<br />"; } ?>
4.foreach loop
The Foreach loop is a variation of the For loop and allows you to iterate over elements in an array. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes:
foreach($array as $value){ // Code to be executed } foreach($array as $key => $value){ // Code to be executed }
<?php $arr = array(1, 2, 3, 4); foreach ($arr as &$value) { $value = $value * 2; } print_r($arr); ?>
2 4 6 8