Multidimensional arrays in PHP


An array that contains one or more arrays is Multidimensional arrays. A multi-dimensional array of each element in the main array can also be an array. And each element in the sub-array can be an array, and so on. Values in the multi-dimensional array are accessed using multiple indexes.

Example

To implement multidimensional arrays in PHP, the code is as follows−

 Live Demo

<?php
$marks = array(
    "kevin" => array (
      "physics" => 95,
      "maths" => 90,
    ),
    "ryan" => array (
      "physics" => 92,
      "maths" => 97,
    ),
);
   echo "Marks for kevin in physics : " ;
   echo $marks['kevin']['physics'] . "
";    echo "Marks for ryan in maths : ";    echo $marks['ryan']['maths'] . "
"; ?>

Output

This will produce the following output−

Marks for kevin in physics : 95
Marks for ryan in maths : 97

Example

Let us now see another example, wherein we are creating 3-dimensional array −

 Live Demo

<?php
   $arr = array(
      array(
         array(100, 150),
         array(200, 250),
      ),
      array(
         array(300, 350),
         array(400, 500),
      ),
   );
   print_r($arr);
?>

Output

This will produce the following output−

Array
(
   [0] => Array
      (
         [0] => Array
            (
               [0] => 100
               [1] => 150
            )
            [1] => Array
               (
                  [0] => 200
                  [1] => 250
               )
      )
      [1] => Array
          (
            [0] => Array
               (
                  [0] => 300
                  [1] => 350
               )
               [1] => Array
                (
                  [0] => 400
                  [1] => 500
                )
        )
)

Updated on: 02-Jan-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements