Loop Through a Two-Dimensional Array in PHP

Description

The following code shows how to loop Through a Two-Dimensional Array.

Example


<!DOCTYPE html>//w  w  w  .  ja v  a 2  s  .co  m
<html>
  <body>
    <h1>Looping Through a Two-Dimensional Array</h1>
    <?php
    
    $myBooks = array(
      array(
        "title" => "XML",
        "author" => "John",
        "pubYear" => 2011
      ),
      array( 
        "title" => "HTML",
        "author" => "Jack",
        "pubYear" => 2012
      ),
      array( 
        "title" => "CSS",
        "author" => "Jason",
        "pubYear" => 2013
      ),
      array( 
        "title" => "Java",
        "author" => "Jane",
        "pubYear" => 2014
      ),
    );
    
    $bookNum = 0;
    
    foreach ( $myBooks as $book ) {
    
      $bookNum++;
      echo "<h2>Book #$bookNum:</h2>";
      echo "<dl>";
    
      foreach ( $book as $key => $value ) {
        echo "<dt>$key</dt><dd>$value</dd>";
      }
    
      echo "</dl>";
    }
    
    ?>

  </body>
</html>

The code above generates the following result.





















Home »
  PHP Tutorial »
    Data Types »




Array
Array Associative
Array Util
ArrayObject
Data Types
Date
Date Format
DateTime
Number
String
String Escape
String Filter
String HTML
String Type
Timezone