Lesson 10 of 32Article19 min
Arrays — Indexed, Associative & Multidimensional
Indexed arrays store lists with numeric keys starting at 0. Create with array() or short syntax [].
Indexed arrays
Indexed arrays store lists with numeric keys starting at 0. Create with array() or short syntax [].
Real-life example: An indexed array is a numbered locker row — locker 0, locker 1, locker 2.
Indexed array
<?php
$courses = ["HTML", "CSS", "PHP", "MySQL"];
echo $courses[0]; // HTML
echo count($courses); // 4
$courses[] = "JavaScript"; // append
?>Associative arrays
Associative arrays use named keys instead of numbers — perfect for user records and config settings.
Real-life example: Associative arrays are labeled drawers — "socks", "shirts", "pants" instead of drawer 1, 2, 3.
Associative array
<?php
$user = [
"id" => 101,
"name" => "Asha",
"email" => "asha@example.com",
"role" => "student"
];
echo $user["name"];
foreach ($user as $key => $val) {
echo "$key: $val\n";
}
?>Multidimensional arrays
Arrays can contain other arrays — useful for tables of students, products, or quiz questions.
Real-life example: A spreadsheet is a 2D array — rows and columns of data.
2D array
<?php
$students = [
["name" => "Asha", "score" => 88],
["name" => "Ravi", "score" => 92],
];
echo $students[1]["name"]; // Ravi
// Useful array functions
$nums = [3, 1, 4, 1, 5];
sort($nums);
print_r($nums);
?>