A multi-dimensional array is an array that is made up of other arrays. I could have an array of cars that contains an array for each car, that tells you the make, model, colour and age, for example.
To create a multidimensional array we start with a normal array:
<?php
$cars = array (
); //an empty array
?>
We take that empty array and fill it with an array of cars. In the array of cars we have given the keys values, like so:
<?php
$cars = array (
array ( 'make'=>'MG',
'model'=>'BGT',
'colour'=>'Damask Red',
'year'=>'1978' ),
array ( 'make'=>'Austin',
'model'=>'Mini',
'colour'=>'Harvest Gold',
'year'=>'1975' ),
array ( 'make'=>'Jaguar',
'model'=>'XJS',
'colour'=>'Carnival Red',
'year'=>'1987' ),
);
?>
To access the information in the array, we use the array name $cars, the number of the array that contains the data, for example, MG would be [0], then we write the name of the key e.g. [model].
To get the age of the Jaguar XJS we write:
echo $cars[2][age];
Below, I have summarized what we have just learned and placed the multidimensional array inside some HTML. Remember, you can create an array in one place and use it where ever and whenever you like.
<html>
<head>
<title>PHP Arrays</title>
</head>
<body>
<?php
$cars = array (
array ( 'make'=>'MG',
'model'=>'BGT',
'color'=>'Damask Red',
'year'=>'1978' ),
array ( 'make'=>'Austin',
'model'=>'Mini',
'colour'=>'Harvest Gold',
'year'=>'1975' ),
array ( 'make'=>'Jaguar',
'model'=>'XJS',
'colour'=>'Carnival Red',
'year'=>'1987' ),
);
echo $cars[2][age];
?>
</body>
</html>