PHP Multidimensional Arrays
A multidimensional array is just an array whose values are arrays. Nesting can go as deep as memory allows — but stop at two or three for sanity.
Build one
PHP
$cars = [
['Volvo', 22, 18],
['BMW', 15, 13],
['Toyota', 5, 2],
];
Access nested values
PHP
echo $cars[0][0]; // Volvo
echo $cars[1][2]; // 13
$grid = [
'a' => ['x' => 1, 'y' => 2],
'b' => ['x' => 3, 'y' => 4],
];
echo $grid['b']['y']; // 4
Loop with destructuring
PHP
foreach ($cars as [$brand, $stock, $sold]) {
echo "$brand: $stock in stock, $sold sold", PHP_EOL;
}
JSON shape
Multidimensional arrays serialise straight to nested JSON:
PHP
echo json_encode($cars, JSON_PRETTY_PRINT); // [["Volvo",22,18],["BMW",15,13],["Toyota",5,2]]
When to reach for an object
Deeply nested arrays are easy to write and hard to read. The moment you have a "shape" with named fields that repeats, model it as a class or a typed DTO:
PHP
class CarRow {
public function __construct(
public string $brand,
public int $stock,
public int $sold,
) {}
}
$cars = [
new CarRow('Volvo', 22, 18),
new CarRow('BMW', 15, 13),
];
Tip: If you find yourself writing
$data['users'][0]['orders'][2]['items'][0], that's a hint the data has earned a class.Example
Example
<?php
$cars = [
['Volvo', 22, 18],
['BMW', 15, 13],
['Toyota', 5, 2],
];
foreach ($cars as [$brand, $inStock, $sold]) {
echo "$brand: $inStock in stock, $sold sold", PHP_EOL;
}
Try it Yourself »
Exercise
Destructure each row in foreach.
foreach ($cars as
$brand, $stock, $sold
) {}
Square brackets.
Discussion
Loading…