Quantcast
Channel: PHP Magic Book - Free PHP Scripts, Tutorials and Downloads » Loops
Viewing all articles
Browse latest Browse all 5

PHP ForEach Loop

$
0
0

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.

<?php
$employeeAges;
$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
?>

PHP ForEach Loop is a post from: PHP Magic Book - Free PHP Scripts, Tutorials and Downloads


Viewing all articles
Browse latest Browse all 5

Latest Images

Trending Articles





Latest Images