Apparel Software

Powered by Blogger.

How PHP Foreach Loop Works?

PHP Foreach Loop


PHP for loops execute a block of code a while specified number of times. The php for loop is used generally when you know in advance that how many times the script should run.

Syntax for Loop

for (init counter; test counter; increment counter) {
The PHP code to be executed;
}

Parameters of above:
init counter: Initialize the loop loop counter value
test counter: Evaluated for each loop iteration and If it evaluates to TRUE, the loop continues. If it evaluates to FALSE than the loop ends.
increment counter: Increases the loop counter value

Example of code

In the example shown below we will display numbers 0 to 20

<html>
<body>

<?php

for($for_variable = 0; $for_variable <= 20; $for_variable++){
echo "The increment increment number is : $for_variable <br>";
}
?>

</body>
</html>

Result of above code

The increment increment number is : 0
The increment increment number is : 1
The increment increment number is : 2
The increment increment number is : 3
The increment increment number is : 4
The increment increment number is : 5
The increment increment number is : 6
The increment increment number is : 7
The increment increment number is : 8
The increment increment number is : 9
The increment increment number is : 10
The increment increment number is : 11
The increment increment number is : 12
The increment increment number is : 13
The increment increment number is : 14
The increment increment number is : 15
The increment increment number is : 16
The increment increment number is : 17
The increment increment number is : 18
The increment increment number is : 19
The increment increment number is : 20

The PHP foreach Loop

The foreach ……………loop execute only on arrays and for  each …….…loop is used to loop through each key/value pair in an array.

Syntax

foreach ($array as $value) {
The php code to be executed;
}

For every php ………………..loop iteration, the value of the present array element is assigned to $value and the array pointer is moved by one, until it reaches the last array element.

The following example of php code demonstrates a loop that will provide the output of the values of the given array ($myname):

Example of Code:

<?php

$name = array("Masiur Rahman", "Alam Rahman ", "Sadekul Rahman ", "Rahman Rahman ");
foreach ($name as $myname){
echo "$myname <br>";
}

?>

Result of above code

Masiur Rahman
Alam Rahman
Sadekul Rahman
Rahman Rahman


Share :

Facebook Twitter Google+ Linkedin
0 Comments "How PHP Foreach Loop Works?"

Back To Top