In this part, we are going to discuss php multidimensional arrays. In our previous part, we have described associative arrays that are a single list of key/value pairs.

PHP for beginners part 12, PHP associative arrays

However, sometimes user need to store values with more than one key. Such values can be stored in multidimensional arrays.

An array containing more than one or more arrays is called multi-dimensional array. We can say it is an array of arrays.

It can be two-dimensional or three-dimensional arrays.

Example

Imagine that you are an owner of a tyres shop. One dimensional array is enough to keep titles and prices. But if you need to keep the tyres from more than one companies you need to use something different. We can use multidimensional arrays to perform such tasks. Below is the table that represents our two-dimensional array. Each row represents the name of the company and each column represents a certain attribute.

Company Name Serial Number Price Service 33 20 Panther 22 50 Company3 77 30

Let’s have a look at the code for above table. In a two-dimensional array, each array has two indexes row and column.

<?php

$tyre = array( array(“service”, 33 , 20),

array(“panther”, 22 , 50),

array(“company3”, 77 , 30)

);

?>

In our previous part, to access data in one-dimensional arrays we have to point to array name and index. The same is true in regards to a two-dimensional array. But the only difference is each element has two indexes row and column. Lets access the values stored in two-dimensional array.

Now the two-dimensional $tyre array contains four arrays, and it has two indices: row and column.

To get access to the elements of the $tyre array we must point to the two indices row and column:

<?php

$tyre = array( array(“service”, 33 , 20),

array(“panther”, 22 , 50),

array(“company3”, 77 , 30)

);

?>

echo $tyre[0][0].”: serial number: “.$tyre[0][1].”, price: “.$tyre[0][2].”.<br>”;

echo $tyre[1][0].”: serial number: “.$tyre[1][1].”, price: “.$tyre[1][2].”.<br>”;

echo $tyre[2][0].”: serial number: “.$tyre[2][1].”, price: “.$tyre[2][2].”.<br>”;

Here is the output for this program.