An array item can be another array. This lets you build tables and nested records.
A list of records
This is the most common shape: a list where each item is an associative array.
<?php
$products = [
["name" => "Notebook", "price" => 80, "stock" => 25],
["name" => "Pen", "price" => 12, "stock" => 100],
["name" => "Bag", "price" => 799, "stock" => 0],
];
echo $products[0]["name"] . "\n";
echo $products[2]["price"];
Notebook
799
Read it from left to right: $products[0] is the first product, and ["name"] is its name.
Loop through it
<?php
$products = [
["name" => "Notebook", "price" => 80],
["name" => "Pen", "price" => 12],
];
foreach ($products as $product) {
echo $product["name"] . ": " . $product["price"] . "\n";
}
Notebook: 80
Pen: 12
A grid (rows and columns)
<?php
$grid = [
[1, 2, 3],
[4, 5, 6],
];
echo $grid[1][2] . "\n"; // row 1, column 2
foreach ($grid as $row) {
echo implode(" ", $row) . "\n";
}
6
1 2 3
4 5 6
Nested records
<?php
$order = [
"id" => 1042,
"customer" => ["name" => "Ravi", "city" => "Surat"],
"items" => [
["sku" => "A1", "qty" => 2],
["sku" => "B7", "qty" => 1],
],
];
echo $order["customer"]["city"] . "\n";
echo count($order["items"]) . " items\n";
echo $order["items"][1]["sku"];
Surat
2 items
B7
Change a nested value
<?php
$order = ["customer" => ["city" => "Surat"]];
$order["customer"]["city"] = "Pune";
$order["customer"]["phone"] = "99999";
print_r($order);
Array
(
[customer] => Array
(
[city] => Pune
[phone] => 99999
)
)
Safe reading with ??
When a nested key might not exist, chain ??.
<?php
$order = ["customer" => ["name" => "Ravi"]];
echo $order["customer"]["email"] ?? "no email";
no email
Pull one column out
<?php
$products = [
["name" => "Notebook", "price" => 80],
["name" => "Pen", "price" => 12],
];
print_r(array_column($products, "price", "name"));
Array
(
[Notebook] => 80
[Pen] => 12
)
array_column() takes one field from every row. The optional third argument sets the keys.