PHP Array foreach loop
In this chapter you will learn:
- How to use foreach to loop through an array
- Syntax to get value using foreach loop
- Syntax to get key and value using foreach loop
- Example - Use foreach loop to get value
- Example - Use foreach to loop through associate array
Description
foreach
is a special kind of looping statement that works only on arrays and objects.
foreach
can be used in two ways.
- retrieve just the value of each element, or
- retrieve the element's key and value.
Syntax to get value
Use foreach to retrieve each element's value, as follows:
foreach ( $array as $value ) { /*from jav a2 s . co m*/
// (do something with $value here)
}
// (rest of script here)
Syntax to get key and value
To use foreach to retrieve both keys and values, use the following syntax:
foreach ( $array as $key => $value ) {
// (do something with $key and/or $value here
} //from ja va 2s .c o m
// (rest of script here)
Example 1
Use foreach loop to get value
<?PHP/* ja va 2 s .c o m*/
$authors = array( "Java", "PHP", "CSS", "HTML" );
foreach ( $authors as $val ) {
echo $val . "\n";
}
?>
The code above generates the following result.
Example 2
Use foreach to loop through associate array
<?php //from jav a2s. co m
$myBook = array( "title" => "Learn PHP from java2s.com",
"author" => "java2s.com",
"pubYear" => 2000 );
foreach ( $myBook as $key => $value ) {
echo "$key \n";
echo "$value \n";
}
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- Why the value is not changed in foreach loop
- How to change the value inside a foreach loop
- Syntax to get value reference in a foreach loop
- Example - change array value with reference in foreach loop
- Note for unset value
Home » PHP Tutorial » PHP Array