agyanadda@gmail.com

PHP Multidimensional Arrays

PHP Arrays 1 min read Updated Dec 1, 2026 Topic 19 of 36

A multidimensional array is an array that contains other arrays. This is exactly how database results look.

$students = [
    ['name' => 'Asha', 'course' => 'BCA', 'fee' => 25000],
    ['name' => 'Ravi', 'course' => 'MCA', 'fee' => 40000],
];

Read a value

$students[1]['name'] → 'Ravi'

Loop through records

foreach ($students as $s) {
    echo $s['name'] . ' – ' . $s['course'];
}

Helpful functions

  • array_column($students, 'name') → ['Asha', 'Ravi']
  • array_sum(array_column($students, 'fee')) → total fees
  • array_filter($students, fn($s) => $s['fee'] > 30000)
  • usort($students, fn($a, $b) => $a['fee'] <=> $b['fee']) — sort by fee

Nested arrays

Arrays can go deeper: $school['classes']['10A']['students'][0]. Keep data no more than 2–3 levels deep for readability.

Example

Example — Student fee report PHP
<?php
$students = [
    ['name' => 'Asha',  'course' => 'BCA', 'fee' => 25000, 'paid' => true],
    ['name' => 'Ravi',  'course' => 'MCA', 'fee' => 40000, 'paid' => false],
    ['name' => 'Neha',  'course' => 'BCA', 'fee' => 25000, 'paid' => true],
    ['name' => 'Aman',  'course' => 'BSc', 'fee' => 18000, 'paid' => false],
];

usort($students, fn($a, $b) => $b['fee'] <=> $a['fee']);

echo '<table border="1" cellpadding="6"><tr><th>Name</th><th>Course</th><th>Fee</th><th>Status</th></tr>';
foreach ($students as $s) {
    $status = $s['paid'] ? '✅ Paid' : '❌ Due';
    echo "<tr><td>{$s['name']}</td><td>{$s['course']}</td><td>₹" . number_format($s['fee']) . "</td><td>$status</td></tr>";
}
echo '</table>';

$due = array_filter($students, fn($s) => !$s['paid']);
echo 'Total fees: ₹' . number_format(array_sum(array_column($students, 'fee'))) . '<br>';
echo 'Pending from: ' . implode(', ', array_column($due, 'name'));

Output: a table sorted by fee (Ravi first), then Total fees: ₹108,000 and Pending from: Ravi, Aman.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which function gets one column of values from an array of records?

Exercise 2 True / False

Database query results are usually multidimensional arrays.

Exercise 3 Fill in the Blank

$data[2]['___'] reads the 'email' of the third record.

Frequently Asked Questions

Use echo '<pre>'; print_r($arr); echo '</pre>'; or var_dump(). In Laravel use dd($arr).