Wednesday , June 28 2017
Home / PHP / PHP for Loop foreach Example Tutorials

PHP for Loop foreach Example Tutorials

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>";
}
?>

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)

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>";
}
?>

BMW
Maybach
Tata
Mitsubishi

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 chandrashekhar

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+ ,

Check Also

php readfile Example Tutorials

In this tutorials, we are going to learn how to read file in php. php …

Leave a Reply

Your email address will not be published. Required fields are marked *