PHP Multidimensional Array: Create, Access and Print

Create, access and print multidimensional (nested) arrays. Edit the code below and press Run to execute it with real PHP in your browser.

Code Editor
Output
Array
(
    [name] => Alice
    [score] => 95
    [subjects] => Array
        (
            [0] => Math
            [1] => Physics
        )

)
Alice (95): Math, Physics
Bob (87): History
Charlie (92): Math, Art
Bob's first subject: History

How this multidimensional array example works

A multidimensional array is an array whose elements are arrays. Each extra pair of brackets goes one level deeper: $students[1]["subjects"][0] is "the first subject of the second student". Below are the common ways to print a multidimensional array, from quick debugging to formatted output.

Print with print_r() inside <pre>

print_r() shows the whole structure. In a browser, wrap it in <pre> so the indentation is kept: echo "<pre>" . print_r($array, true) . "</pre>";

<?php
$matrix = [[1, 2], [3, 4]];
print_r($matrix);

Output:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => 2
        )

    [1] => Array
        (
            [0] => 3
            [1] => 4
        )

)

Print with var_dump() to see types

<?php
$row = ["id" => 7, "price" => 9.5, "tags" => ["new"]];
var_dump($row);

Output:

array(3) {
  ["id"]=>
  int(7)
  ["price"]=>
  float(9.5)
  ["tags"]=>
  array(1) {
    [0]=>
    string(3) "new"
  }
}

Print as JSON

<?php
$data = ["user" => ["name" => "Ann", "roles" => ["admin", "editor"]]];
echo json_encode($data, JSON_PRETTY_PRINT);

Output:

{
    "user": {
        "name": "Ann",
        "roles": [
            "admin",
            "editor"
        ]
    }
}

Print a 2D array as a grid with nested foreach

<?php
$matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
];
foreach ($matrix as $row) {
    foreach ($row as $cell) {
        echo str_pad($cell, 4);
    }
    echo "\n";
}
echo "Center: " . $matrix[1][1];

Output:

1   2   3
4   5   6
7   8   9
Center: 5

Print rows as an HTML table

Escape values with htmlspecialchars() when printing data into HTML.

<?php
$rows = [
    ["name" => "Alice", "score" => 95],
    ["name" => "Bob", "score" => 87],
];
echo "<table>\n<tr><th>" . implode("</th><th>", array_keys($rows[0])) . "</th></tr>\n";
foreach ($rows as $row) {
    echo "<tr><td>" . implode("</td><td>", array_map('htmlspecialchars', $row)) . "</td></tr>\n";
}
echo "</table>";

Output:

<table>
<tr><th>name</th><th>score</th></tr>
<tr><td>Alice</td><td>95</td></tr>
<tr><td>Bob</td><td>87</td></tr>
</table>

Print any depth with a recursive function

<?php
function printTree(array $items, int $depth = 0): void {
    foreach ($items as $key => $value) {
        $indent = str_repeat("  ", $depth);
        if (is_array($value)) {
            echo "$indent$key:\n";
            printTree($value, $depth + 1);
        } else {
            echo "$indent$key: $value\n";
        }
    }
}

printTree([
    "site" => "phpcompiler.net",
    "menu" => ["home" => "/", "docs" => ["functions" => "/php-functions/", "examples" => "/examples/"]],
]);

Output:

site: phpcompiler.net
menu:
  home: /
  docs:
    functions: /php-functions/
    examples: /examples/

Get one column, sort and search

<?php
$students = [
    ["name" => "Alice", "score" => 95],
    ["name" => "Bob", "score" => 87],
    ["name" => "Charlie", "score" => 92],
];
echo implode(", ", array_column($students, "name")) . "\n";

usort($students, fn($a, $b) => $b["score"] <=> $a["score"]);
echo "Top: " . $students[0]["name"] . "\n";

$i = array_search("Bob", array_column($students, "name"));
echo "Bob is now at index $i";

Output:

Alice, Bob, Charlie
Top: Alice
Bob is now at index 2

Multidimensional Array FAQ

How do I print a multidimensional array in PHP?

For debugging use print_r($array) (wrapped in <pre> in a browser) or var_dump($array). For formatted output loop with nested foreach, or use json_encode($array, JSON_PRETTY_PRINT).

How do I access a value in a nested array?

Chain the keys: $data["user"]["roles"][0]. Use $data["user"]["email"] ?? "none" to avoid warnings for missing keys.

How do I loop through a multidimensional array?

Use a foreach inside a foreach, or a recursive function when the depth is unknown.

Why does echo show "Array"?

echo cannot print arrays; it converts them to the string "Array" with a warning. Use print_r(), var_dump(), implode() or json_encode().