PHP Loop Through Multidimensional Array

In this chapter you will learn:

  1. How to Loop Through Multidimensional Array
  2. Syntax to Loop Through Multidimensional Array
  3. 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:

  1. What Is a Function?
  2. What is function parameter
  3. What is return value form a function
  4. Why Functions Are Useful
Home » PHP Tutorial » PHP Array
PHP Array
PHP Create Indexed Array
PHP Create Associative Arrays
PHP Array Operator
PHP Access Array Element
PHP Change Array Element
PHP Create Array using Square Bracket
PHP Array Element Loop Through
PHP Array foreach loop
PHP Change Array Values with foreach
PHP Array Multidimensional
PHP Access Element in Multidimensional Array
PHP Loop Through Multidimensional Array