PHP Loops

|

Loops are used to repeat statement or block of statement more than one time. The idea of a loop is to do something over and over again until the task has been completed


In PHP we have the following looping statements:

For Loop:

For loops are useful constructions to loop through a finite set of data, such as data in an array.
Syntax:

for ( initialization; conditional statement; increment/decrement){

statement(s);

}

1. Initialization—You can pass in an already assigned variable or assign a value to the variable in the for statement.

2. The condition required to continue the for loop— The statements are executed until the given condition goes false.

3. Statement to modify the counter on each pass of the loop.



Example:


for ($i=1; $i<=10; $i++)

{

echo "Hello World
";


}

?>

Foreach Loop:

Foreach loops allow you to quickly traverse through an array.

$array = array("name" => "Jet", "occupation" => "Bounty Hunter" );

foreach ($array as $val) {

echo "

$val";



}

Prints out:

Jet



Bounty Hunter



You can also use foreach loops to get the key of the values in the array:

foreach ($array as $key => $val) {

echo "

$key : $val";



}


Prints out:

name : Jet



occupation : Bounty Hunter


While Loop:

While loops are another useful construct to loop through data. While loops continue to loop until the expression in the while loop evaluates to false. A common use of the while loop is to return the rows in an array from a result set. The while loop continues to execute until all of the rows have been returned from the result set.

Syntax:

while (condition){

statement(s);


Example:



$i=1;

while($i<=9)

{

echo "The number is " . $i . "
";


$i++;

}

?>

Do-While Loop:

Do while loops are another useful loop construct. Do while loops work exactly the same as normal while loops, except that the script evaluates the while expression after the loop has completed, instead of before the loop executes, as in a normal while loop.

The important difference between a do while loop and a normal while loop is that a do while loop is always executed at least once. A normal while loop may not be executed at all, depending on the expression. The following do while loop is executed one time, printing out $i to the screen:

$i = 0;

do {

print $i;

} while ($i>0);

Whereas the following is not executed at all:

$i = 0;

while($i > 0) {

print $i;

}
Arrays:

An array is a data structure that stores one or more values in a single value. PHP supports both numerical arrays (array items are indexed by their numerical order) as well as associative arrays (array items are indexed by named keys).
Example:

$a = array(1, 2, 3, 4);

//$a[0] = 1

//$a[1] = 2

//$a[2] = 3

//$a[3] = 4

$b = array("name"=>"Fred", "age" => 30);

//$b['name'] = "Fred"

//$b['age'] = 30

}