Multidimensional Arrays
On this page
Nested Arrays
Multidimensional arrays are arrays that contain arrays. They are common when representing lists of records (like DB rows) or nested JSON payloads.
<?php $users = [ ['id' => 1, 'name' => 'Ozan'], ['id' => 2, 'name' => 'Ayse'], ]; echo $users[1]['name']; // Ayse
Iterating a List of Records
This pattern appears constantly in backend code: you fetch rows and loop through them.
<?php
foreach ($users as $user) {
echo $user['id'] . ' - ' . $user['name'] . PHP_EOL;
}
Nested Key Access Safely
Deep access can cause undefined index warnings. Use ?? at each level or normalize data before use.
<?php
$payload = [
'user' => [
'profile' => [
'city' => 'Ankara'
]
]
];
$city = $payload['user']['profile']['city'] ?? 'Unknown';
echo $city;
Building a Data Structure
Sometimes you build nested structures for JSON APIs.
<?php
$response = [
'ok' => true,
'data' => [
'items' => [
['id' => 1, 'title' => 'PHP Intro'],
['id' => 2, 'title' => 'Arrays'],
],
'pagination' => [
'page' => 1,
'limit' => 20,
],
],
];
echo json_encode($response);
Production Tip
Nested arrays are flexible but can become fragile. Keep structures consistent and validate inputs. For complex nested payloads, consider DTO objects and dedicated validation.