Skip to main content

PHP - Multidimensional Arrays

When the items of an array are themselves arrays, whether one or several, you have a multidimensional array.

PHP lets you nest them two, three, four, five levels deep or further. In practice, though, most people find anything beyond three levels hard to manage.


PHP - Two-dimensional Arrays

A two-dimensional array is simply an array whose items are arrays. Add another layer, so that the inner arrays hold arrays of their own, and you get a three-dimensional array.

This shape suits data that comes in rows and columns. Here is what it looks like:

Access two-dimensional array elements

Reading a value from $cars takes two indices, the first for the row and the second for the column:

Prompt
Write a PHP script that creates a two-dimensional array of car brands with stock and sold numbers (Volvo 22/18, BMW 15/13, Saab 5/2, Land Rover 17/15), then echoes each row showing brand name, stock, and sold values.
Output: PHP script

Two-dimensional array definition

Each inner array is one row of a table, with the brand, the number in stock and the number sold:

index.php
<?php
$cars = array (
  array("Volvo", 22, 18),
  array("BMW", 15, 13),
  array("Saab", 5, 2),
  array("Land Rover", 17, 15)
);
?>

PHP - Looping Through Multidimensional Arrays

Going through a multidimensional array takes a for or a foreach loop.

The number of dimensions tells you how many indices it takes to reach a single element:

  • Two dimensions mean two indices
  • Three dimensions mean three indices

Loop with nested for loops

One for loop nested in another visits every element of $cars. The outer one moves through the rows, the inner one through the columns, and each element is still reached with both indices:

Prompt
Write a PHP script that creates a two-dimensional array of car brands with stock and sold numbers (Volvo 22/18, BMW 15/13, Saab 5/2, Land Rover 17/15), then uses nested for loops to display each row number and its elements in an HTML unordered list.
Output: PHP script

Loop with nested foreach loops

Nested foreach loops can do the same job without any index numbers. This time the values are printed as an HTML table:

Prompt
Write a PHP script that creates a two-dimensional array of car brands with stock and sold numbers (Volvo 22/18, BMW 15/13, Saab 5/2, Land Rover 17/15), then uses nested foreach loops to display the data in an HTML table with headers Brand, Stock, and Sold.
Output: PHP script