1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

An Introduction to Loops in PHP

By

3 of 3

FOREACH Loops
To understand FOREACH loops you have to remember what we learned about arrays. If you recall an array (unlike a variable) contains a group of data. When using a loop with an array, instead of having a counter that goes until proven false the FOREACH loop continues until it has used all values in the array. So for example if an array contained 5 pieces of data, then the FOREACH loop would execute 5 times. More uses for arrays and FOREACH loops will become apparent when you start importing data from MySQL.

A FOREACH loop is phrased like this: FOREACH (array as value) { what to do; }

Here is an example of a FOREACH loop:

 <?php 
$a = array(1, 2, 3, 4, 5);
foreach ($a as $b)
{
print $b . " ";
}
?>

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

Related Video
Basic PHP Syntax
Using PHP With HTML
  1. About.com
  2. Technology
  3. PHP / MySQL
  4. PHP Functions
  5. PHP Foreach() Loop Tutorial - Intro to Loops in PHP

©2014 About.com. All rights reserved.