Arrays · Lesson 4 of 7
Multidimensional Arrays
Represent nested records and collections with arrays inside arrays.
Lesson
An array can contain other arrays to represent rows, groups, or nested data. Access each level deliberately and check whether expected keys exist before reading external data. For complex data that needs behavior or invariants, a class or value object is often clearer than deeply nested arrays.
The example reads one field from the first row in a small table.
Further guidance
Choose list indexes for ordered items and descriptive keys for named fields. Check whether an expected key exists before reading it, and preserve keys when their association matters during sorting or filtering. Use a small fixture to test empty, single-item, and nested data.
Practice task: Create a fresh example for Multidimensional Arrays. Predict the result before running it, then change one input and explain why the result changes. Test a normal case and one boundary or invalid case where it applies. Compare your output with the example and note one rule you would use in a real project.
Code examples
Multidimensional Arrays
PHP
$rows = [
['name' => 'Tea', 'price' => 3],
['name' => 'Coffee', 'price' => 4],
];
echo $rows[0]['name'], ': $', $rows[0]['price'];
Expected output
Tea: $3
Key points
- Represent nested records and collections with arrays inside arrays.
- Use descriptive keys for records and indexes for ordered lists.
- Check keys and bounds before accessing data that may be absent.
Your learning progress
Finish this lesson
Optional practice
PHP playground
This site does not execute learner-provided PHP code. Connect a secured PHP sandbox service before enabling code execution.
Execution is disabled. No code is sent to a server.