PHP Multidimensional Array
Last Updated : 17 Mar 2025
An array of arrays is called a multidimensional array. Every element in a PHP array may be another array. If an array contains values or key-value pairs with values of single scalar types, it is said to be one-dimensional. If every element in an array consists of one or more scalar values, the array is said to be two-dimensional.
A PHP array may also be a two-dimensional associative array, where the value is another associative array, and each member of the outer array is a key-value pair.
Syntax:
PHP Multidimensional Array Example
Let's see a simple example of PHP multidimensional array to display following tabular data. In this example, we are displaying 3 rows and 3 columns.
| Id | Name | Salary |
|---|---|---|
| 1 | Sam | 400000 |
| 2 | John | 500000 |
| 3 | Rick | 300000 |
Example
Output:
1 Sam 400000 2 John 500000 3 Rick 300000
Performing Iterations on a 2D Array
To go over every element in a 2D array, two nested loops will be required. For array traversal, the foreach loop works well. Similar to a tabular representation of data in rows and columns is a 2D array.
1. Traversing Indexed 2D Array
The example that follows demonstrates how to replicate a 2D array in tabular form:
Example
Output:
1 2 3 4 10 20 30 40 100 200 300 400
2. Traversing Associative 2D Array
Two stacked foreach loops may also be used to explore a 2D associative array. Unpack each row of the outer array in the row-key and row-value variables, then use the inner foreach loop to cycle over each row's contents.
Example
Output:
row1 key11 => val11 key12 => val12 key13 => val13 row2 key21 => val21 key22 => val22 key23 => val23 row3 key31 => val31 key32 => val32 key33 => val33
Accessing the 2D Array's Elements
It is also possible to access and edit an element in a 2D array using the $arr[$key] syntax. The phrase
"$arr[$i][$j]" may be used to obtain and assign the jth element in the ith row of a 2D indexed array.
Indexed 2D Array Example
Example
Output:
Value at [2][2]: 300
Associative 2D Array Example
To access or change the value of a desired column in a 2D associative array, we must utilize the row key and key-value variables.
Example
Output:
Value at row2 - key22 is: val22
Recursive Multidimensional Array Traversal
The recursive function in the following code calls itself if a given key's value is another array. Any array sent as an input to this method will be traversed, and all of its k-v pairings will be shown.
Function Example
Example:
Let us use a 2D associative array as an argument to showarray() function:
Example
Output:
item1 => value1 item2 => value2 item3 => value3 item4 => value4 item5 => value5 item6 => value6 item7 => value7 item8 => value8 item9 => value9
Next TopicPHP Array Functions