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["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34"; foreach( $employeeAges as $key => $value){
echo "Name: $key, Age: $value <br />";
}
Display:
Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34

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

foreach syntax: $something as $key => $value
This crazy statement roughly translates into: For each element of the $employeeAges associative array I want to refer to the key as $key and the valueas $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["Lisa"] = "28";
$employeeAges["Jack"] = "16";
$employeeAges["Ryan"] = "35";
$employeeAges["Rachel"] = "46";
$employeeAges["Grace"] = "34";foreach( $employeeAges as $name => $age){
echo "Name: $name, Age: $age <br />";
}
Display:
Name: Lisa, Age: 28
Name: Jack, Age: 16
Name: Ryan, Age: 35
Name: Rachel, Age: 46
Name: Grace, Age: 34

Credit: tizag.com