Star Hoster
Photoshop Tutorials
Anonymous Web Surfing
Funny Jokes
Myspace Friends
Open Treasure Chest
Building in Paradise


December 1, 2005

PHP For Each Loop

Filed under: Intro PHP Tutorials — phpdeveloper @ 12:29 am

For Each Loop

Imagine that you have an associative array that you want to iterate through. PHP provides an easy way to use every element of an array with the Foreach statement.

In plain english this statement will do the following:

For each item in the specified array execute this code.

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.

Example

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

PHP Code:

$employeeAges;
$employeeAges[”Ray”] = “29″;
$employeeAges[”Mason”] = “19″;
$employeeAges[”Roger”] = “35″;

foreach( $employeeAges as $key => $value)
{
echo “Name: $key, Age: $value
“;
}

Display:

Name: Ray, Age: 29
Name: Mason, Age: 19
Name: Roger, Age: 35

The syntax of the foreach statement is a little strange, so let’s talk about it some.

Syntax: $something as $key => $value

This statement roughly translates into: For each element of the $employeeAges associative array I want to refer to the key as $key and the value as $value.

The operator “=>” represents the relationship between a key and value. You can imagine that the key points => to the value. In our example we named the key $key and the value $value. However, it might be easier to think of it as $name and $age. Below our example does this and notice how the output is identical because we only changed the variable names that refer to the keys and values.

PHP Code:

$employeeAges;
$employeeAges[”Ray”] = “29″;
$employeeAges[”Mason”] = “19″;
$employeeAges[”Roger”] = “35″;

foreach( $employeeAges as $name => $age)
{
echo “Name: $name, Age: $age
“;
}

Name: Ray, Age: 29
Name: Mason, Age: 19
Name: Roger, Age: 35

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

You must be logged in to post a comment.