1. Home
  2. Computing & Technology
  3. PHP / MySQL

An Introduction to Loops in PHP

By Angela Bradley, About.com

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

Index: An Introduction to Loops in PHP

  1. WHILE Loops
  2. FOR Loops
  3. FOREACH Loops

3 of 3

Explore PHP / MySQL

More from About.com

  1. Home
  2. Computing & Technology
  3. PHP / MySQL
  4. PHP Functions
  5. PHP Tutorial - PHP FOREACH - PHP Loops

©2008 About.com, a part of The New York Times Company.

All rights reserved.