PHP Arrays: Indexed, Associative and Multidimensional Arrays
What is an array in PHP?
An array in PHP is an ordered map: a single variable that holds many values, each stored under a key. Keys can be integers, giving an indexed array, or strings, giving an associative array, and values can themselves be arrays. PHP provides dozens of built-in functions to search, transform, filter and sort arrays.
Indexed, associative and multidimensional arrays
An indexed array uses automatic integer keys starting at 0. An associative array uses keys you choose, usually strings. A multidimensional array holds arrays inside arrays, which is how rows from a database usually arrive.
<?php
$colours = ['red', 'green', 'blue']; // indexed
echo $colours[1]; // green
$student = ['name' => 'Asha', 'city' => 'Pune']; // associative
echo $student['city']; // Pune
$students = [ // multidimensional
['id' => 1, 'name' => 'Asha', 'marks' => 87],
['id' => 2, 'name' => 'Ravi', 'marks' => 72],
['id' => 3, 'name' => 'Meera', 'marks' => 94],
];
echo $students[2]['name']; // Meera
$colours[] = 'yellow'; // append
unset($student['city']); // remove a key
echo count($students); // 3Arrays are copied when assigned or passed to a function, so changing the copy leaves the original unchanged. The data you send to the browser as JSON usually starts life as one of these nested arrays.
Checking and looping through arrays
foreach ($student as $key => $value)walks every key and value in order.isset($a['k'])is false when the key is missing or its value isnull;array_key_exists()checks only the key.in_array($value, $a, true)searches values; always passtruefor strict comparison, otherwise"1e1"matches10.array_keys(),array_values()andarray_search()return keys, values or the key of a match.
How PHP converts array keys
PHP quietly converts some keys, which surprises many beginners. A string that looks like a whole decimal number, such as "8", becomes the integer 8. Booleans become 0 or 1, null becomes an empty string, and a float is truncated to an integer (with a deprecation notice when it has a fractional part). Two keys that convert to the same value overwrite each other.
<?php
$rooms = ['8' => 'Lab', 8 => 'Library', true => 'Office', '08' => 'Store'];
var_dump($rooms);
// [8 => 'Library', 1 => 'Office', '08' => 'Store']The string "08" stays a string because of its leading zero. When keys come from user input or a CSV file, convert them explicitly so you know which type you are working with.
Transforming data with array_map, array_filter and array_reduce
These three functions replace many hand-written loops. Note the argument order: array_map() takes the callback first, while array_filter() and array_reduce() take the array first.
<?php
declare(strict_types=1);
$names = array_map(fn (array $s): string => $s['name'], $students);
// ['Asha', 'Ravi', 'Meera']
$passed = array_filter($students, fn (array $s): bool => $s['marks'] >= 75);
$passed = array_values($passed); // re-index keys 0, 1
$total = array_reduce(
$students,
fn (int $carry, array $s): int => $carry + $s['marks'],
0
);
echo round($total / count($students), 1); // 84.3array_filter() keeps the original keys, so the filtered list above had keys 0 and 2 until array_values() renumbered it. Gaps in keys matter when you encode an array as JSON: a list with gaps becomes a JSON object instead of an array. The arrow functions used here are explained in the guide to PHP functions.
Sorting arrays and extracting columns
PHP sorting functions change the array in place and return a boolean, not the sorted array. Choose the function by whether you need to keep keys.
| Function | Sorts by | Keeps keys? |
|---|---|---|
| sort / rsort | Value, ascending / descending | No, re-indexes |
| asort / arsort | Value, ascending / descending | Yes |
| ksort / krsort | Key, ascending / descending | Yes |
| usort | Your comparison function | No |
| uasort / uksort | Your function, by value / by key | Yes |
<?php
// Highest marks first, using the spaceship operator
usort($students, fn (array $a, array $b): int => $b['marks'] <=> $a['marks']);
echo $students[0]['name']; // Meera
$namesById = array_column($students, 'name', 'id');
// [3 => 'Meera', 1 => 'Asha', 2 => 'Ravi']
echo max(array_column($students, 'marks')); // 94The <=> operator returns -1, 0 or 1, which is exactly what a comparison callback needs. array_column() pulls one field out of every row and can use another field as the key, which makes lookups by ID fast.
Destructuring, spread and merging arrays
Destructuring unpacks array values into variables in one statement. The spread operator ... copies the elements of one array into another; since PHP 8.1 it also works with string keys, where later keys overwrite earlier ones.
<?php
[$first, $second] = ['Asha', 'Ravi'];
[$first, $second] = [$second, $first]; // swap
['name' => $name, 'marks' => $marks] = $students[0];
foreach ($students as ['name' => $n, 'marks' => $m]) {
echo $n . ': ' . $m . PHP_EOL;
}
$defaults = ['theme' => 'light', 'lang' => 'en'];
$chosen = ['lang' => 'hi'];
$settings = [...$defaults, ...$chosen]; // ['theme' => 'light', 'lang' => 'hi']
$palette = [...$colours, 'purple'];Destructuring makes code that handles database rows much shorter, because you can pull out exactly the fields you need inside the foreach header. Missing keys produce a warning and a null, so destructure only arrays whose shape you control.
For string keys, array_merge() and spread both let the later array win. The + operator is different: it keeps the left-hand value and only adds keys that are missing, which suits filling in defaults.
Recommended practices for working with arrays
- Use short
[]syntax and keep every element in an array the same shape. - Prefer
array_map(),array_filter()andarray_column()to manual loops when they read more clearly. - Always use strict mode in
in_array()andarray_search(). - Call
array_values()after filtering a list that will become JSON. - When an array grows many fixed keys passed around the application, turn it into a small class with typed properties.
Readable array code matters because arrays carry most of the data in a typical PHP application, from form input in $_POST to query results and configuration. A short chain of well-named functions tells the next developer what the code does at a glance.
PHP 8.4 also added helpers such as array_find(), array_any() and array_all(); check your server version before relying on them.
Practical exercise: a class results report
Create results.php with an array of at least six students, each with id, name, city and marks.
- Print the class average with
array_reduce(), rounded to one decimal. - List students who scored 75 or more, sorted from highest to lowest with
usort(). - Build an
id => namelookup witharray_column()and print one name by ID. - Group students by city into a nested array using a
foreachloop. - Merge a defaults array with user settings using spread and print the result with
print_r().
You are done when every output matches what you calculate by hand and json_encode() of the passed list produces a JSON array, not an object. Keep the file under Git version control as you go. Arrays are a core topic in the PHP foundation course.
Common mistakes
- Passing arguments to
array_map()andarray_filter()in the wrong order. - Writing
$sorted = sort($list);and gettingtrueinstead of a sorted array. - Forgetting that
array_filter()preserves keys, which leaves gaps that turn a JSON list into an object. - Using
in_array()without strict mode, so loosely equal values produce false matches. - Using
isset()to test for a key whose value may legitimately benull. - Using
+to merge arrays and expecting the right-hand values to win.
Frequently asked questions
Is a PHP array the same as a list in other languages?
Not quite. A PHP array is an ordered map, so the same type serves as a list, a dictionary and a stack. array_is_list(), added in PHP 8.1, tells you whether keys run 0, 1, 2 in order.
How do I remove duplicates from an array?
Use array_unique(), then array_values() if you need clean numeric keys. For arrays of rows, build an array keyed by the unique field instead.
How large can a PHP array be?
It is limited by the memory_limit setting rather than a fixed count. For very large datasets, process rows in batches or use generators instead of loading everything at once.
Should I use arrays or objects for data?
Arrays suit simple, short-lived data such as query results. Objects suit data with rules and behaviour, because typed properties catch mistakes that array keys cannot.