Online admissions open for the SEO, web development and networking & cybersecurity courses. Enquire for the next batch.

PHP Arrays: Indexed, Associative and Multidimensional Arrays

5 min read Updated By the SkillNewton team

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);         // 3

Arrays 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 is null; array_key_exists() checks only the key.
  • in_array($value, $a, true) searches values; always pass true for strict comparison, otherwise "1e1" matches 10.
  • array_keys(), array_values() and array_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.3

array_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.

FunctionSorts byKeeps keys?
sort / rsortValue, ascending / descendingNo, re-indexes
asort / arsortValue, ascending / descendingYes
ksort / krsortKey, ascending / descendingYes
usortYour comparison functionNo
uasort / uksortYour function, by value / by keyYes
<?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'));     // 94

The <=> 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.

  1. Use short [] syntax and keep every element in an array the same shape.
  2. Prefer array_map(), array_filter() and array_column() to manual loops when they read more clearly.
  3. Always use strict mode in in_array() and array_search().
  4. Call array_values() after filtering a list that will become JSON.
  5. 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 => name lookup with array_column() and print one name by ID.
  • Group students by city into a nested array using a foreach loop.
  • 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() and array_filter() in the wrong order.
  • Writing $sorted = sort($list); and getting true instead 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 be null.
  • 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.

Want to Learn This Properly?

The PHP Web Development: Foundation & Practical Implementation (Online) turns guides like this into practised skills, with projects on real websites.

WhatsApp Call Us Now

Free counselling

Send an Enquiry

Tell us which course you are interested in. We reply by email or phone with the next batch and how to enrol.

Protected by reCAPTCHA. Google Privacy and Terms apply.

We reply by email or phone within working hours. No spam.