In PHP, what does it mean that an array is an ordered map, and how do indexed and associative arrays differ?
answer
- one type for lists and dictionaries
- keys are only int or string
- insertion order, not key order
- values of any type, nesting allowed
- indexed is just keys 0..n-1
basics
~20 sA PHP array is one ordered map from int or string keys to values of any type. Indexed and associative arrays are the same type: an indexed array just has keys 0, 1, 2, and every array keeps insertion order.
solid answer
~40 sPHP has a single `array` type, and the manual describes it as an **ordered map**: every element is a key/value pair, keys are either `int` or `string`, values can be anything, including other arrays. An "indexed" array such as `['a', 'b']` is simply one whose keys happen to be `0` and `1`; an "associative" array such as `['id' => 7]` uses string keys; one array may mix both. "Ordered" means the array remembers **insertion order**, and `foreach` walks that order, not the numeric order of the keys: `[3 => 'c', 1 => 'a']` iterates `c` then `a`. Lookup by key goes through a hash, so `$a['id']` does not scan the array. The same type therefore serves as a list, a dictionary, a stack, a queue or a record.
code
php · 14 lines<?php
$mixed = ['a', 'b', 'label' => 'x'];
$mixed[] = 'c'; // key 2
var_dump(array_keys($mixed)); // [0, 1, 'label', 2]
$order = [3 => 'c', 1 => 'a'];
$order[2] = 'b';
foreach ($order as $k => $v) {
echo "$k=$v "; // 3=c 1=a 2=b
}
$sparse = [];
$sparse[1000] = 'x';
echo count($sparse); // 1go deeper
Recall the three properties: keys are int or string, values are anything, and every array keeps insertion order for foreach.
Explain that indexed and associative are conventions over one type, how overwrite and unset affect order, and why key lookup beats value search.
Use the model when reviewing code, spotting order-dependent logic, accidental mixed keys and value scans that a keyed lookup table should replace.
Decide when the general-purpose array is enough and when a typed collection or value object would make a domain model clearer and safer.
## One type, many roles PHP has one built-in collection type for sequences and dictionaries alike: `array`. The manual calls it an **ordered map**, a structure that associates keys with values and also remembers the order in which the pairs were added. The same type is used as: - a **list** (`['red', 'green', 'blue']`), - a **dictionary** (`['host' => 'db1', 'port' => 5432]`), - a **record** or row from a database fetch, - a **stack** or **queue**, through `array_push()`/`array_pop()` and `array_shift()`, - a **tree**, by nesting arrays inside arrays. ## Keys and values The two sides of each pair follow different rules: | Side | Allowed types | Notes | |---|---|---| | key | `int` or `string` only | other scalar types are converted; arrays and objects are rejected | | value | any type | scalars, `null`, arrays, objects, closures, resources | Because only `int` and `string` survive as keys, a key written as `true`, `8.7` or the numeric string `"8"` is converted to an `int` before it is stored. Those casting rules are a topic of their own, and they are the source of most surprises with PHP arrays. ## Indexed versus associative is a convention PHP does not have two array kinds. The words describe what the keys look like: 1. An **indexed** array has integer keys, usually `0` to `n-1`, created by listing values without keys: `['a', 'b', 'c']`. 2. An **associative** array has meaningful keys, usually strings: `['sku' => 'A-1', 'qty' => 3]`. 3. A **mixed** array has both, and is perfectly legal: `['a', 'b', 'label' => 'x']` has keys `0`, `1` and `'label'`. Functions do not care which kind you meant. `count()` counts pairs, `foreach` yields every pair, and `$a[] = $v` appends with the next integer key whether or not string keys are present. ## What "ordered" guarantees Order in a PHP array is **insertion order**: - `foreach` visits pairs in the order they were first added. - Overwriting an existing key changes its value but keeps its position. - Removing a key with `unset()` removes the pair; the others keep their relative order. - Integer keys do not sort themselves: after `$a[5] = 'x'; $a[1] = 'y';`, iteration yields `x` first. Only explicit sorting functions reorder an array, and some of them renumber the keys while others keep them. ## Lookup cost Reading `$a[$key]` or checking `array_key_exists($key, $a)` hashes the key and jumps to it, so the cost does not grow with the array's size in the normal case. Searching by **value**, with `in_array()` or `array_search()`, walks the elements one by one. That difference is why PHP code often builds a lookup array keyed by the value it needs to find. ## Why interviewers ask The question checks whether a candidate has the right mental model before any trickier topic: - someone who thinks of PHP arrays as fixed-size, index-only sequences will be surprised that `$a[1000] = 'x'` on an empty array creates exactly one element, not 1 001; - someone who thinks associative arrays are unordered will write code that depends on order by accident, or will not trust it when it matters; - someone who knows keys are cast will spot the bug when `'1'` and `1` turn out to be the same key. A good answer names the three properties together: int-or-string keys, any values, insertion order.
- If you overwrite an existing key in the middle of an array, does the element move to the end?No. Assigning to an existing key replaces the value in place and keeps its original position in the iteration order. Only removing the key with `unset()` and adding it again would place it at the end.
- Why do PHP developers often build an array keyed by the values they need to look up?Checking a key with `array_key_exists()` or reading `$a[$key]` goes through the array's hash, while `in_array()` compares values one by one. Keying a lookup table by the value you search for turns repeated linear scans into direct key lookups, at the cost of building the table once.
saying these in an interview costs you the question
- Associative arrays in PHP do not keep any reliable order.
- Indexed and associative arrays are two different types in PHP.
- A PHP array cannot mix integer and string keys.
- foreach walks integer keys in ascending numeric order.
- Assigning $a[1000] on an empty array allocates 1001 slots.