In PHP, a multidimensional array is an array that contains one or more arrays as its elements. These nested arrays are called subarrays, and can contain elements of any data type, including strings, integers, booleans, and even other arrays.
Multidimensional arrays are useful for storing and manipulating data that has a complex structure, such as data that represents a grid or a table. They can be used to store data for a matrix, a database, or a hierarchical structure, such as a tree.
Here is an example of a multidimensional array in PHP:
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
echo $matrix[0][0]; // Outputs 1
echo $matrix[1][1]; // Outputs 5
echo $matrix[2][2]; // Outputs 9
In this example, the $matrix
array has three elements, each of which is an array. These subarrays are accessed using the array indices in square brackets. The elements of the subarrays are accessed using a second set of square brackets.
You can also create a multidimensional array using the array
function:
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
// or
$matrix = array();
$matrix[0] = array(1, 2, 3);
$matrix[1] = array(4, 5, 6);
$matrix[2] = array(7, 8, 9);
To access and manipulate the elements of a multidimensional array, you can use multiple sets of square brackets to specify the indices of the elements.
For example, to access the element at row 2, column 3 of the $matrix
array, you would use the following syntax:
echo $matrix[1][2]; // Outputs 6