php - Looping Structure
Looping Structure - php:
Loop structures in PHP is an iterative control
structures that involves executive the same block of code a specified num ber
of times. Loops that iterate for fixed no of times is also called as Bounded
loops. PHP supports four types of loops. Refer Figure 7.1 for flow chart of for
Loop Structure.
● for
Loop
● While
Loop
● foreach
Loop
● Do
While Loop
The for loop is used when you know how many times
you want to execute a statement or block of statements.
for (init counter; test counter; increment counter) {
code to be executed;
}
● init counter: Initialize the loop initial counter
value
● Test counter: Evaluated for every iteration of
the loop. If it evaluates to TRUE, the loop continues. If it evaluates to
FALSE, the loop ends.
● Increment counter: Increases the loop counter
value.
Example:
<?php
for ($i = 0; $i<= 10; $i++) {
echo “The number is: $i<br>”;
}
?>
foreach loop is exclusively available in PHP and is
mainly used for looping through the values of an array. The loop iteration
deepens on each KEY Value pair in the Array. For each, loop iteration the value
of the current array element is assigned to $value variable and the array
pointer is advanced by one, until it reaches the end of the array element.
Refer Figure 7.2.
foreach ($array as $value) {
code to be executed;
}
<?php
$Student_name = array(“Magilan”,
“Iniyan”, “Nilani”, “Sibi”, “Shini”);
foreach ($Student_name as $value)
{
echo “$value <br>”;
}
?>
The while loop executes a block of code as long as
the condition specified in the while statement evaluates to true. Refer Figure
7.3
while (condition is true)
{
code to be executed;
}
<?php
$Student_count = 10;
$student_number=1;
while($student_number<=
$Student_count)
{
echo “The student number is:
$student_number<br>”; $student_number++;
}
?>
The do.. while loop is always very similer to the
while loop but executes the block of code at least once before evaluating the
condition. Here the condition is evaluated only at the time of exit of each
iteration. Refer Figure 7.4.
do {
code to be executed;
} while (condition is true);
<?php
$Student_count = 10;
$student_number=1;
do
{
echo “The student number is:
$student_number<br>”;
$student_number++;
}
while($student_number<=
$Student_count)
?>
Related Topics
Privacy Policy, Terms and Conditions, DMCA Policy and Compliant
Copyright © 2018-2023 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.