PHP Array Multidimensional

In this chapter you will learn:

  1. What is multidimensional array
  2. Example for a multidimensional array
  3. Example - Create two-dimensional array with array() function

Description

A multi-dimensional array can have array as its value.

An array that contains other arrays is a two-dimensional array. If those arrays also contain arrays, then the top-level array is a three-dimensional array, and so on.

Example

The following code uses array operator ([]) to create an two-dimensional array. The key of the first level is Java and PHP.


<?PHP//jav  a 2s.  co m
$book['Java'] = array("Name"=>"Java Book", "Price"=> 1.2, "OnSale"=>"No");
$book['PHP'] = array("Name"=>"PHP Book", "Price"=>5.3, "OnSale"=>"Yes");
var_dump($book);
?>

The code above generates the following result.

Example 2

The following script creates a simple two-dimensional array called $myBooks , then displays its contents using print_r().


<?php //from  j a va 2  s .  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 
    ), 
  ); 

  print_r ( $myBooks ); 
?>  

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. How to access element in multidimensional array
  2. Syntax to access element in multidimensional array
  3. Example - Access elements in multi-dimensional array
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