PHP how to make a multidimensional array

Learn how to create multi-dimensional arrays in PHP with an example. Understand the basics and gain the confidence to use them in your code.

Creating Multidimensional Arrays

Creating multidimensional (or nested) arrays in PHP is relatively easy. You can create an array that contains other arrays, and access the elements in the sub-arrays by using multiple indexes.

For example, let's look at a two-dimensional array with three columns and two rows. We can create this array using the following code:

$myArray = array ( 
   array("John", "Smith", 21), 
   array("Jane", "Doe", 23) 
 );

The array contains two elements, each of which is another array. Each of these two sub-arrays has three elements. We can access the elements in the sub-arrays by using two indexes. The first index specifies the row, and the second index specifies the column. For example, to access the "Smith" element, we would use the following code:

echo $myArray[0][1];
// output: Smith

We can also create three-dimensional arrays, four-dimensional arrays, and so on. The same principle applies - we can access elements in the sub-arrays by using more indexes. For example, let's look at a three-dimensional array with three columns and two rows, and two levels:

$myArray = array ( 
   array ( 
      array("John", "Smith", 21), 
      array("Jane", "Doe", 23) 
   ), 
   array ( 
      array("John", "Smith", 42), 
      array("Jane", "Doe", 44) 
   ) 
);

We can access the "Doe" element in the second level and first row by using the following code:

echo $myArray[1][0][1];
// output: Doe

We can continue nesting arrays as deep as we need. This can be useful for representing hierarchical data structures, such as menus, trees, and more.

Answers (0)