Multidimensional Arrays in PHP: syntax and example

Multidimensional Arrays in PHP:
In previous post Arrays in PHP we learned Arrays and types of arrays.
We understood the concept of regular array that is indexed array, it is also called numeric array. We understood associative array.

Now we are going to understand Multidimensional array.
A multidimensional array is an array containing one or more arrays. It is also called array of array.

A 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. Values in the multi-dimensional array are accessed using multiple index.

Two-dimensional Arrays:
A two-dimensional array is an array of arrays (a three-dimensional array is an array of arrays of arrays).




example:
<?php
$students=array(
          array('Vanesh', 'MCA', '78'),
          array('Ganesh', 'MCM', '83'),
          array('Ramesh', 'MSC', '64'),
);

echo $students[0][0]." ".$students[0][1]." ".$students[0][2]. "<br/>";
echo $students[1][0]." ".$students[1][1]." ".$students[1][2]. "<br/>";
echo $students[2][0]." ".$students[2][1]." ".$students[2][2]. "<br/>";

?>


output:
Vanesh MCA 78
Ganesh MCM 83
Ramesh MSC 64

We can print this array using foreach loop as:

<?php
$students=array(
          array('Vanesh', 'MCA', '78'),
          array('Ganesh', 'MCM', '83'),
          array('Ramesh', 'MSC', '64'),
);
foreach($students as $key => $val){
  foreach($val as $v){
      echo $v." ";
    }
  echo "<br/>";
}
?>

output:
Vanesh MCA 78
Ganesh MCM 83
Ramesh MSC 64

3 comments:

  1. Pretty good post. I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I'll be subscribing to your feed and I hope you post again soon. Big thanks for the useful info.
    Tech Startups

    ReplyDelete
  2. Hi Robert,
    Thank you for appreciating Technology Park's efforts.
    Technology park is trying to help the IT freshers to get their concepts cleared. Will try to post something valuable in next post.
    Thank you.

    ReplyDelete
  3. Very nice post .Your post is really helpful for us .By your post we can take information about it.
    gclub
    goldenslot
    gclub online

    ReplyDelete

We are here to listen you, Comment your valueable opinion...!!!