Multidimensional Array in PHP

In PHP, a multidimensional array is an array that contains one or more arrays as its elements. These arrays can themselves contain other arrays, creating a nested or hierarchical structure. Multidimensional arrays are useful for storing and manipulating complex data structures, such as matrices, tables, or lists of records with multiple attributes.

Here's how you can create and work with a multidimensional array in PHP:

Example
// Creating a multidimensional array
$matrix = array(
    array(1, 2, 3),
    array(4, 5, 6),
    array(7, 8, 9)
);

// Accessing elements
echo $matrix[0][0]; // Output: 1
echo $matrix[1][1]; // Output: 5
echo $matrix[2][2]; // Output: 9

// Modifying elements
$matrix[1][2] = 10;
echo $matrix[1][2]; // Output: 10

// Adding elements
$matrix[2][] = 11;
echo $matrix[2][3]; // Output: 11

// Getting the number of rows and columns
$numRows = count($matrix);
$numCols = count($matrix[0]);
echo "Number of rows: $numRows, Number of columns: $numCols <br>";

// Iterating over the array
foreach ($matrix as $row) {
    foreach ($row as $value) {
        echo $value . " ";
    }
    echo "<br>";
}

In this example:

  • We create a multidimensional array $matrix containing three arrays, each representing a row of a matrix.
  • We access elements of the array using their row and column indices ($matrix[0][0], $matrix[1][1], $matrix[2][2]).
  • We modify an element of the array.
  • We add a new element to one of the rows.
  • We use the count() function to determine the number of rows and columns in the array.
  • We iterate over the array using nested foreach loops to output each element.

Multidimensional arrays can have any number of dimensions, allowing for the creation of increasingly complex data structures. They are widely used in PHP for tasks such as representing tabular data, storing hierarchical information, and working with nested structures like JSON or XML data.

Next Article ❯