How to use Multi-dimensional Array in PHP

In this article, I will explain how the Multi-dimensional Array can be used in PHP.
  • 2974

Array in PHP

  • An array is a data structure that stores one or more similar type of values in a single value.
  • Each element in the array has its own index so that it can be easily accessed.
  • An array in PHP is a collection of key/value pairs.

Multi-dimensional Array

  • Multi-dimensional array, 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.
  • Multidimensional array is a structure which holds various arrays in an array.
  • Multi-dimensional array value are accessed using multiple index.

Example

In this example we create a two dimensional array to store marks of three students in three subjects:

<html>

<body>

<h2 style="color: blueviolet;">Multi-dimensional Array example</h2>

    <?php

    $marksheet = array(

         "Nitin" => array

          (

          "physics" => 82,        

          "maths" => 70,          

           "chemistry" => 89       

          ),

        "Sachin" => array

        (

         "physics" => 70,

         "maths" => 85,

         "chemistry" => 89

        ),

        "Priyanka" => array

        (

        "physics" => 81,

        "maths" => 72,

        "chemistry" => 90

        )

        );

   /* Multi-dimensional array values accessing */

   echo "Marks for Nitin in physics : " ;

   echo $marksheet['Nitin']['physics'] . "<br />";

   echo "Marks for Sachin in maths : ";

   echo $marksheet['Sachin']['maths'] . "<br />";

   echo "Marks for Priyanka in chemistry : " ;

   echo $marksheet['Priyanka']['chemistry'] . "<br />";

    ?>

</body>

</html>

 

Output

multidimension.jpg 
You may also want to read these related articles here
 
Ask Your Question 
 
Got a programming related question? You may want to post your question here
 
© 2019 DotNetHeaven. All rights reserved.