PHP Multidimensional Arrays
Multidimensional arrays are arrays that contain other arrays. They're essential for representing complex data structures like tables, matrices, hierarchical data, and records from databases or APIs.
What are Multidimensional Arrays?
A multidimensional array is simply an array where each element can be another array. The most common type is the 2D array (array of arrays).
| Dimensions | Description | Access Pattern |
|---|---|---|
| 2D Array | Array of arrays (like a table) | $arr[row][col] |
| 3D Array | Array of 2D arrays | $arr[x][y][z] |
| Nested Assoc. | Associative arrays within arrays | $arr["key"]["subkey"] |
2D Arrays (Matrices)
A 2D array is like a table with rows and columns:
<?php
// 3x3 matrix
$matrix = [
[1, 2, 3], // Row 0
[4, 5, 6], // Row 1
[7, 8, 9] // Row 2
];
// Access: $matrix[row][column]
echo $matrix[0][0]; // 1 (first row, first column)
echo $matrix[1][2]; // 6 (second row, third column)
echo $matrix[2][1]; // 8 (third row, second column)
?>
Click Run to execute your code
Array of Associative Arrays
This is the most common real-world pattern - a list of records:
<?php
// Array of user records (like database rows)
$users = [
["id" => 1, "name" => "Alice", "email" => "[email protected]"],
["id" => 2, "name" => "Bob", "email" => "[email protected]"],
["id" => 3, "name" => "Carol", "email" => "[email protected]"]
];
// Access specific user's data
echo $users[0]["name"]; // Alice
echo $users[1]["email"]; // [email protected]
// Loop through all users
foreach ($users as $user) {
echo "{$user['name']}: {$user['email']}\n";
}
?>
- Database query results
- API responses (JSON decoded)
- Form data with multiple items
- Configuration files
Nested Associative Arrays
Deeply nested structures for complex hierarchical data:
<?php
$company = [
"name" => "TechCorp",
"address" => [
"street" => "123 Main St",
"city" => "San Francisco",
"state" => "CA",
"zip" => "94102"
],
"departments" => [
"engineering" => [
"manager" => "Alice",
"team_size" => 15
],
"sales" => [
"manager" => "Bob",
"team_size" => 10
]
]
];
// Access nested values
echo $company["name"]; // TechCorp
echo $company["address"]["city"]; // San Francisco
echo $company["departments"]["engineering"]["manager"]; // Alice
?>
Traversing Multidimensional Arrays
Using Nested Foreach
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
// Nested foreach
foreach ($matrix as $rowIndex => $row) {
foreach ($row as $colIndex => $value) {
echo "[$rowIndex][$colIndex] = $value\n";
}
}
?>
Using Nested For Loops
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
$rows = count($matrix);
$cols = count($matrix[0]);
for ($i = 0; $i < $rows; $i++) {
for ($j = 0; $j < $cols; $j++) {
echo $matrix[$i][$j] . " ";
}
echo "\n";
}
?>
Real-World Examples
Click Run to execute your code
Modifying Nested Arrays
<?php
$data = [
"users" => [
["name" => "Alice", "age" => 25],
["name" => "Bob", "age" => 30]
]
];
// Add a new user
$data["users"][] = ["name" => "Carol", "age" => 28];
// Modify existing user
$data["users"][0]["age"] = 26;
// Add a new property to existing user
$data["users"][1]["city"] = "New York";
// Remove a user
unset($data["users"][0]);
// Reindex after removal
$data["users"] = array_values($data["users"]);
?>
Checking Nested Keys
<?php
$config = [
"database" => [
"host" => "localhost",
"port" => 3306
]
];
// Check if nested key exists
if (isset($config["database"]["host"])) {
echo "Host: " . $config["database"]["host"];
}
// Safe access with null coalescing
$timeout = $config["database"]["timeout"] ?? 30;
echo "Timeout: $timeout"; // 30 (default)
// Check multiple levels
function getNestedValue($arr, $keys, $default = null) {
foreach ($keys as $key) {
if (!isset($arr[$key])) {
return $default;
}
$arr = $arr[$key];
}
return $arr;
}
$host = getNestedValue($config, ["database", "host"], "127.0.0.1");
?>
Common Mistakes
1. Accessing non-existent nested keys
<?php
$data = ["user" => ["name" => "John"]];
// โ WRONG: Will cause errors
echo $data["user"]["email"]["domain"];
// Warning: Undefined array key "email"
// โ
CORRECT: Check before accessing
if (isset($data["user"]["email"]["domain"])) {
echo $data["user"]["email"]["domain"];
}
// Or use null coalescing
echo $data["user"]["email"]["domain"] ?? "N/A";
?>
2. Confusing index order
<?php
$table = [
["A1", "B1", "C1"],
["A2", "B2", "C2"]
];
// โ WRONG: Accessing [column][row]
echo $table[0][1]; // "B1", not "A2"
// โ
CORRECT: Remember it's [row][column]
echo $table[1][0]; // "A2" (row 1, column 0)
?>
3. Modifying copy instead of original
<?php
$users = [
["name" => "Alice", "score" => 85]
];
// โ WRONG: $user is a copy
foreach ($users as $user) {
$user["score"] += 10; // Doesn't modify original
}
print_r($users); // Score still 85!
// โ
CORRECT: Use reference
foreach ($users as &$user) {
$user["score"] += 10; // Modifies original
}
unset($user); // Don't forget!
print_r($users); // Score is now 95
?>
Exercise: Product Inventory
Task: Create and manage a product inventory system.
Requirements:
- Create a nested array with product categories
- Each category contains multiple products
- Each product has: id, name, price, stock
- Calculate total inventory value per category
- Find products with low stock (< 10 items)
Show Solution
<?php
$inventory = [
"electronics" => [
["id" => 1, "name" => "Laptop", "price" => 999.99, "stock" => 15],
["id" => 2, "name" => "Mouse", "price" => 29.99, "stock" => 50],
["id" => 3, "name" => "Keyboard", "price" => 79.99, "stock" => 5]
],
"clothing" => [
["id" => 4, "name" => "T-Shirt", "price" => 19.99, "stock" => 100],
["id" => 5, "name" => "Jeans", "price" => 49.99, "stock" => 8],
["id" => 6, "name" => "Jacket", "price" => 89.99, "stock" => 3]
]
];
echo "=== Inventory Value by Category ===\n\n";
foreach ($inventory as $category => $products) {
$categoryValue = 0;
foreach ($products as $product) {
$categoryValue += $product["price"] * $product["stock"];
}
echo ucfirst($category) . ": $" . number_format($categoryValue, 2) . "\n";
}
echo "\n=== Low Stock Alert (<10 items) ===\n\n";
foreach ($inventory as $category => $products) {
foreach ($products as $product) {
if ($product["stock"] < 10) {
echo "โ ๏ธ {$product['name']} ({$category}): ";
echo "Only {$product['stock']} left!\n";
}
}
}
?>
Summary
- 2D Arrays: Arrays of arrays, like tables
- Access:
$arr[row][col]or$arr["key"]["subkey"] - Records: Array of associative arrays for data records
- Nesting: Arrays can be nested to any depth
- Traversal: Use nested foreach or for loops
- Safety: Always check with
isset()or?? - Modification: Use
&reference in foreach to modify
What's Next?
Now that you can work with complex array structures, let's learn about Array Functions I - PHP's built-in functions for searching, checking, and extracting array data!
Enjoying these tutorials?