PHP for Loop foreach Example Tutorials

By | 2017-01-31T10:11:38+00:00 January 25th, 2017|PHP|0 Comments

PHP for loop (s) are designed to work with iterative numbers. A block of code will be executed for a specified number of times.

PHP for Loop :

The PHP for loop demands that the programmer must know how many times the script is needed to run.

Syntax :


for (initialize counter; test counter; increment counter) {
Block of code for execution;
}

The php for loop parameters in the syntax are detailed below :

Initialize counter: Declares the first value of the counter

Test counter: Declares the condition to be tested. The loop runs for as long as this condition is true.

Increment counter: increments the initialized value each time the loop runs until the parameter is test counter parameter is false.

PHP for loop Example :


<?php

for ($i = 0; $i <= 5; $i++) {
echo "I am running $i time(s)<br>";
}
?>

[box type=”success” align=”alignleft” class=”” width=”100%”]

I am running 0 time(s)
I am running 1 time(s)
I am running 2 time(s)
I am running 3 time(s)
I am running 4 time(s)
I am running 5 time(s)

[/box]

PHP foreach Loop :

PHP for loops and other loops are applicable for all kinds of variables. PHP foreach loops are specifically meant for the arrays in PHP.

The PHP foreach loop loops through the elements or key/value pairs in arrays.

foreach Syntax :


foreach ($array as $value) {
Code for execution within an array;
}

Every loop iteration targets an element of an array until every member is assigned/modified.

Example :


<?php

$cars = array("BMW", "Maybach", "Tata", "Mitsubishi");

foreach ($cars as $brand) {
echo "$brand <br>";
}
?>

[box type=”success” align=”alignleft” class=”” width=”100%”]

BMW
Maybach
Tata
Mitsubishi

[/box]

The for loops and foreach loops have great applicability in any situation. As stated in the previous tutorials, PHP gives the developer all tools that he will require to exploit his /her creativity.

 

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment