PHP Multidimensional Array

In this tutorial, learn how to create a multidimensional array in PHP and the methods to traverse through its elements. PHP multidimensional array is useful to create an array with user-defined keys to store data. It has only manually assigned keys for each element.

What is PHP Multidimensional Array?

A multidimensional array is an array that contains another array with each index. It is called an array of array or array inside another array. The elements have a certain level of array and sub-array that are accessed by using multiple indices.

There can be two, three, four, and more dimensions in a multidimensional array. The more the number of dimensions in a multidimensional array, the more is the number of indices that increases more difficultly to access elements.

In this tutorial, you will learn a two-dimensional array that can be accessed with two indices.

How to Create Multidimensional Array in PHP

You can create a multidimensional array using associative arrays in which keys are manually assigned within array(). It is an array that contains an associative array inside an array. However, you can also use the indexed array inside the array in the same manner to create a two-dimensional array in PHP.

Output

First data contains 2 Cycle, 5 Bike, and 9 Car.
Second data contains 3 Cycle, 6 Bike, and 10 Car.
Third data contains 5 Cycle, 8 Bike, and 12 Car.

Traversing Through Multidimensional Array Elements Using Foreach Loop

Traversing through a multidimensional array is the process of getting each inner array and the data inside them. After accessing all the array elements, it collects the keys with their relevant values. The multidimensional array can contain an indexed or associative array as the elements of it.

For two dimensional array, you can use the nested loop as given below to access the elements. It can be For loop with Foreach loop or For loop inside to get the required data.

Using the Foreach loop in PHP:-

Output

Row 0 contains below data
Cycle:2
Bike:5
Car:9

Row 1 contains below data
Cycle:3
Bike:6
Car:10

Row 2 contains below data
Cycle:5
Bike:8
Car:12

Find Length of a Multidimensional Array in PHP

The length of a multidimensional array is the number of elements present in it. To find the length of an associative array, you can use the PHP sizeof() function to get the length of the array. It takes an argument as the multidimensional array variable checks the size of the array as given below:

Output

3

The above example uses the sizeof() to get the number of elements in a multidimensional array. The output shows that the length of the multidimensional array is 3 as there are 3 elements in it.