How to use Multidimensional Array Function Using PHP?

Multidimensional Array simply means Array inside Array, in PHP we can also create Multidimensional Array, Multidimensional Array array can be of both types Indexed Multidimensional Array, or Associative Multidimensional Array. It depends on our need which one we have to use.

In Multidimensional Array we give an array instead of value for each key or index, and then inside that array we store the data according to our need.

PHP Multidimensional Array Syntax

/* define using array() function */
$arr_var = array(
'key1'=>array('value1', 'value3'),
'key2'=>array('value1', 'value3'), 
);
/* define using [] brackets */
$arr_var2 = [
'key1'=>array('value1', 'value3'),
'key2'=>array('value1', 'value3'), 
];

Note – It is not necessary that there is only one array inside an array, you can create any number of nested arrays according to your need. The syntax given above is just two dimensional array syntax.

PHP Multidimensional Array Example

<?php
$students = [
'student1' => ['name' => 'Rahul', 'age'=>25, 'class'=> 9],
'student2' => ['name' => 'Gargi', 'age'=>28, 'class'=> 10],
'student3' => ['name' => 'Jyoti', 'age'=>19, 'class'=> 12],
];
/* now it's time to access them */
echo "student 1 : ".$students['student1']['name']." and class : ".$students['student1']['class']."<br>";
echo "student 3 : ".$students['student3']['name']." and class : ".$students['student3']['class'];
?>

Output

student 1 : Rahul and class : 9
student 3 : Jyoti and class : 12

So in this way we create Multidimensional Array in PHP, although the given example is Two Multidimensional Associative Array, you can also create Two Multidimensional Indexed Array in the same way, and to access index number (0 in place of key) , 1 , 2 etc.. ).