Home Tutorials IT Jobs Source Codes Certifications Discussion Forum
  PHP Tutorials
PHP Introduction
PHP Installation
Syntax
Variables
Echo
Strings
Operators
Comments
Require
Include
If...Else
Switch
Forms
Functions
Arrays
While Loop
For Loop
For Each
Do While
Post & Get
File Create
File Open
File Close
File Write / Read
File Delete
File Append
File Truncate
File upload
PHP str replace
PHP substr_replace
PHP Capitalization
PHP Explode
PHP Implode
   IT Jobs
Software Jobs
Networking Jobs
   Model Question Papers
BE Computer Science
MCA
BCA
Others
 
   

PHP - foreach loop

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

 

<< Previous | Next >>
Home  |  About us  | Privacy  |  Disclaimer  |  Contact us |  Advertise with us | Our Link Partners
All Rights Reserved 2009, CodeTeller.com