PHP Loop Through Multidimensional Array
In this chapter you will learn:
- How to Loop Through Multidimensional Array
- Syntax to Loop Through Multidimensional Array
- Example - Loop Through Multidimensional Array
Description
Multidimensional arrays are basically arrays nested inside other arrays, we can loop through multidimensional arrays using nested loops!
Syntax
We can use the following nested foreach statements to loop through multidimensional array.
foreach ( $myBooks as $book ) { //from j a v a2s. c om
foreach ( $book as $key => $value ) {
}
}
Example
The following example uses two nested foreach loops to loop through the $myBooks array.
<?php /*from ja v a 2s.c o m*/
$myBooks = array(
array(
"title" => "Learn PHP from java2s.com",
"author" => "java2s.com",
"pubYear" => 2000
),
array(
"title" => "Learn Java from java2s.com",
"author" => "JavaAuthor",
"pubYear" => 2001
),
array(
"title" => "Learn HTML from java2s.com",
"author" => "HTMLAuthor",
"pubYear" => 2002
),
array(
"title" => "Learn CSS from java2s.com",
"author" => "CSSAuthor",
"pubYear" => 2003
),
);
$bookNum = 0;
foreach ( $myBooks as $book ) {
$bookNum++;
echo "Book #$bookNum:";
foreach ( $book as $key => $value ) {
echo "$key :$value \n";
}
}
?>
The code above generates the following result.
Next chapter...
What you will learn in the next chapter:
- What Is a Function?
- What is function parameter
- What is return value form a function
- Why Functions Are Useful
Home » PHP Tutorial » PHP Array