PHP foreach
In this chapter you will learn:
- What is foreach loop
- foreach loop Syntax
- Example - Loop array with foreach loop
- Example - Iterating through a multidimensional array with foreach
- Example - Iterating Through Object Properties
Description
PHP has the following loop keywords: foreach, while, for, and do...while.
The foreach loop is designed to work with arrays. You can also use foreach with objects, in which case it iterates over each public variable of that object.
Syntax
The most basic use of foreach extracts only the values from each array element, like this:
foreach($array as $val) {
print $val;
}
Here the array $array is looped through, and its values are extracted into $val. In this situation, the array keys are ignored completely.
You can also use foreach to extract keys, like this:
foreach ($array as $key => $val) {
print "$key = $val\n";
}
Example
Loop array with foreach loop
<?PHP/* j a v a 2 s .c om*/
$list = array("A", "B", "C", "D", "E");
print "<ul>\n";
foreach ($list as $value){
print " <li>$value</li>\n";
} // end foreach
print "</ul>\n";
?>
The code above generates the following result.
Example 2
Iterating through a multidimensional array with foreach()
<?PHP/* ja v a 2 s. c o m*/
$flavors = array('Japanese' => array('hot' => 'A',
'salty' => 'B'),
'Chinese' => array('hot' => 'D',
'pepper-salty' => 'C'));
foreach ($flavors as $culture => $culture_flavors) {
foreach ($culture_flavors as $flavor => $example) {
print "A $culture $flavor flavor is $example.\n";
}
}
?>
The code above generates the following result.
Example 3
Iterating Through Object Properties
<?PHP// ja v a2s . c o m
class Person {
public $FirstName = "Jack";
public $MiddleName = "M.";
public $LastName = "Smith";
private $Password = "myPassword";
public $Age = 29;
public $HomeTown = "PHP";
public $FavouriteColor = "Purple from java2s.com";
}
$bill = new Person( );
foreach($bill as $key => $value) {
echo "$key is $value\n";
}
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- What is PHP while loop
- Syntax for while loop
- Example - while loop with integer counter
- Example - Infinite Loops
- Example - infinite while loop with break statement