Multidimensional Arrays
Build and navigate arrays of arrays.
Multidimensional Arrays is a free PHP Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the PHP Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Multidimensional Arrays
A multidimensional array is an array where each element is itself an array. Common for structured data like database results or config trees.
2D Array Creation
Create and access a two-dimensional array:
<?php
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
echo $matrix[1][2]; // 6 (row 1, col 2)
$matrix[0][0] = 99;
echo $matrix[0][0]; // 99Array of Associative Arrays
Database result sets are often arrays of associative arrays:
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
['id' => 2, 'name' => 'Bob', 'role' => 'user'],
['id' => 3, 'name' => 'Carol', 'role' => 'user'],
];
echo $users[0]['name']; // Alice
echo count($users); // 3Iterating 2D Arrays
Use nested foreach to iterate all rows and columns:
<?php
$products = [
['name' => 'Widget', 'price' => 9.99],
['name' => 'Gadget', 'price' => 24.99],
];
foreach ($products as $product) {
echo $product['name'] . ': $' . $product['price'] . PHP_EOL;
}Accessing Nested Keys Safely
Use the null coalescing operator to safely access nested keys that may not exist:
<?php
$config = [
'database' => ['host' => 'localhost', 'port' => 3306],
'cache' => ['driver' => 'redis'],
];
$port = $config['database']['port'] ?? 3306;
$password = $config['database']['password'] ?? '';
echo $port; // 3306
echo $password; // (empty)Adding to Nested Arrays
Add elements deep inside a multidimensional array:
<?php
$app = [];
$app['settings']['theme'] = 'dark';
$app['settings']['lang'] = 'en';
$app['users'][] = ['name' => 'Alice'];
$app['users'][] = ['name' => 'Bob'];
echo count($app['users']); // 2
echo $app['settings']['theme']; // darkarray_column()
array_column() extracts a single column from a 2D array:
<?php
$users = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob'],
['id' => 3, 'name' => 'Carol'],
];
$names = array_column($users, 'name');
print_r($names); // ['Alice', 'Bob', 'Carol']
// Re-index by id
$byId = array_column($users, null, 'id');
echo $byId[2]['name']; // BobSorting a 2D Array
Sort rows by a field value using usort():
<?php
$products = [
['name' => 'C Item', 'price' => 30],
['name' => 'A Item', 'price' => 10],
['name' => 'B Item', 'price' => 20],
];
usort($products, fn($a, $b) => $a['price'] <=> $b['price']);
foreach ($products as $p) {
echo $p['name'] . PHP_EOL; // A Item, B Item, C Item
}Recursive Operations with array_walk_recursive
Apply a callback to every leaf in a nested array with array_walk_recursive():
<?php
$data = ['a' => 'hello', 'b' => ['c' => 'world', 'd' => 'php']];
array_walk_recursive($data, function(&$val) {
$val = strtoupper($val);
});
print_r($data);
// ['a'=>'HELLO', 'b'=>['c'=>'WORLD','d'=>'PHP']]JSON and Multidimensional Arrays
PHP multidimensional arrays map directly to JSON objects and arrays:
<?php
$data = [
'user' => ['id' => 1, 'name' => 'Alice'],
'scores' => [95, 87, 92],
'active' => true,
];
$json = json_encode($data, JSON_PRETTY_PRINT);
echo $json;
$decoded = json_decode($json, true); // true = assoc array
echo $decoded['user']['name']; // Alicearray_merge vs array_replace for Nested
array_merge is not recursive; use array_replace_recursive to merge nested arrays properly:
<?php
$defaults = ['db' => ['host' => 'localhost', 'port' => 3306]];
$custom = ['db' => ['host' => 'production.server.com']];
$config = array_replace_recursive($defaults, $custom);
echo $config['db']['host']; // production.server.com
echo $config['db']['port']; // 3306 — preserved from defaultsQuick Check
Which function extracts a single column of values from a 2D array?
Recap: Multidimensional Arrays
Key points:
- Nest arrays to any depth
- Use
??to safely access missing nested keys array_column()extracts a column or re-indexes by a keyusort()with a comparator sorts by any fieldarray_walk_recursive()for deep transformsarray_replace_recursive()for deep merging
Frequently asked questions
Is the “Multidimensional Arrays” lesson free?
Yes — the full text of “Multidimensional Arrays” is free to read here on the web, and the PHP Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the PHP Academy course, upgrade to CoddyKit PRO.
What will I learn in “Multidimensional Arrays”?
Build and navigate arrays of arrays. You practise PHP Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start PHP Academy?
No prior experience is required. PHP Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Multidimensional Arrays” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this PHP Academy lesson?
Yes. Every PHP Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Indexed and Associative Arrays
- Multidimensional Arrays
- Sorting and Searching Arrays
- Array Transformation Functions