Saturday, 15 December 2012

Foreach Loop in PHP

Foreach Loop in PHP

PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easyway to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

Foreach loop Syntax:
foreach (array_expression as $value)
statement
foreach (array_expression as $key => $value)
statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.

As of PHP 5, it is possible to iterate objects too. As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

Example 1:
<?php
        $browsers = array ("Firefox", "Internet Explorer", "Opera");
        echo "<select>";
        foreach($browsers as $browser)
        {
                echo "<option name='$browser'>$browser</option>";
        }
        echo "</select>";
?>

Example 2:
Once you understand that concept you can then use the FOREACH loop to do more practical things. Let's say an array contains the ages of 5 family members. Then we will make a FOREACH loop that will determine how much it costs for each of them to eat on a buffet that has varied prices based on age. We will use the following pricing system: Under 5 is free, 5-12 years costs $4 and over 12 years is $6.

<?php
$t = 0;
$age = array(33, 35, 13, 8, 4);
foreach ($age as $a)
 {
 if ($a < 5)
  {$p = 0;}
 else
  {
  if ($a <12)
   {$p = 4;}
  else
   {$p = 6;}
  }
$t = $t  + $p;
print "$" . $p . "<br>";
 }
print "The total is: $" . $t;  
?>

0 comments:

Post a Comment