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:
output:
Vanesh MCA 78
Ganesh MCM 83
Ramesh MSC 64
We can print this array using foreach loop as:
output:
Vanesh MCA 78
Ganesh MCM 83
Ramesh MSC 64
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