HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP Multidimensional Arrays

A multidimensional array is an array containing one or more arrays. PHP supports multidimensional arrays that are two, three, four, five, or more levels deep. However, arrays deeper than three levels are hard to manage for most people.


1. Two-Dimensional Arrays

A two-dimensional array is like a table with rows and columns. Imagine we have the following data:

Name Stock Sold
Volvo2218
BMW1513
Saab52

We can store this data in a 2D array like this:

<?php
    $cars = [
        ["Volvo", 22, 18],
        ["BMW", 15, 13],
        ["Saab", 5, 2]
    ];
?>

2. Accessing Elements

To access an element, we must point to the two indices (row and column):

<?php
    echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";
    echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";
?>

3. Looping Through Nested Arrays

To display the entire contents of a multidimensional array, we use a nested loop — a loop inside another loop.

<?php
    for ($row = 0; $row < 3; $row++) {
        echo "<p><b>Row number $row</b></p>";
        echo "<ul>";
        for ($col = 0; $col < 3; $col++) {
            echo "<li>".$cars[$row][$col]."</li>";
        }
        echo "</ul>";
    }
?>
Depth vs. Complexity: While you can technically nest arrays infinitely, it becomes extremely difficult to debug. If your data structure requires more than 3 levels, consider using Objects or a Database.
Pro Tip: Multidimensional arrays are perfect for representing data that comes from a database query, where each row is an array of column values.

Key Points to Remember

  • A multidimensional array is simply an array of arrays.
  • 2D arrays are the most common, used for tabular data.
  • Use multiple brackets (e.g., [0][1]) to access inner data.
  • Iteration requires nested loops (one for each dimension).
  • Keep complexity low; avoid nesting too many levels deep.