Monday 22 April 2013

PHP - For Loops


   For Loops

The for loop is used when you know in advance how many times the script should run.
The for loop is simply a while loop with a bit more code added to it. The common tasks that are covered by a for loop are:

1.  Set a counter variable to some initial value.
2.  Check to see if the conditional statement is true.
3.  Execute the code within the loop.
4.  Increment a counter at the end of each iteration through the loop.

Syntax:


For (init; condition; increment)

  {
 code to be executed;
  }



Example:

<html>
<body>


<?php
for ($i=1; $i<=5; $i++)
  {
  echo "The number is " . $i . "<br>";
  }
?>



</body>
</html>



Output:

The number is 1

The number is 2
The number is 3
The number is 4
The number is 5


   The foreach Loop


The foreach loop is used to loop through arrays.
Imagine that you have an associative array that you want to iterate through. PHP provides an easy way to use every element of an array with the For each statement.
We have an associative array that stores the names of people in our company as the keys with the values being their age.
We want to know how old everyone is at work so we use a Foreach loop to print out everyone's name and age.

 

PHP Code:


$employeeAges;
$employeeAges["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";

foreach( $employeeAges as $key => $value){
         echo "Name: $key, Age: $value <br />";
}

Display:

Name: Lisa, Age: 28

Name: Jack, Age: 16
Name: Ryan, Age: 35

Name: Rachel, Age: 46

Name: Grace, Age: 34


Example:

<html>
<body>


<?php
$x=array("one","two","three");
foreach ($x as $value)
  {
  echo $value . "<br>";
  }
?>



</body>
</html>


Output:

one

two
three

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More