PHP ForEach Loop

by Hiroshi on June 21, 2008

in For Each Loop, Loops, PHP Basics

PHP provides an easy way to use every element of an array with the For each statement. For each executes the code at each item in the specified array. While a For Loop and While Loop will continue until some condition fails, the For Each loop will continue until it has gone through every item in the array.

We have an associative array that stores the names of people in a 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.

$employeeAges["Imran"] = "18";
$employeeAges["Kamran"] = "26";
$employeeAges["Jawad"] = "35";
$employeeAges["Javed"] = "36";
$employeeAges["Rashid"] = "32";
foreach( $employeeAges as $key => $value)
	echo "Name: $key, Age: $value <br />";
// Output:
// Name: Imran, Age: 18
// Name: Kamran, Age: 26
// Name: Jawad, Age: 35
// Name: Javed, Age: 36
// Name: Rashid, Age: 32

Related Posts

Previous post:

Next post: