Indexed and Associative Arrays
PHP has only one array type, an ordered map, but it is used in two conventional ways: as an indexed array, where keys are sequential integers starting at 0, and as an associative array, where keys are meaningful strings (or arbitrary integers) mapped to values. Internally both are the same ordered-hash-table structure, so PHP does not enforce a strict distinction; you can freely mix string and integer keys in a single array. This flexibility makes arrays PHP's workhorse data structure, used for lists, dictionaries, sets, stacks, queues, and even simple records before objects are introduced.
Cricket analogy: PHP's single array type is like a scorebook that can be read as a chronological over-by-over list (indexed) or as a player-name-to-runs table (associative) — same underlying ledger, two ways of reading it, and you can mix both freely.
Creating and Accessing Arrays
Arrays are created with the short [] syntax (or the older array() function) and can be nested to represent complex structures. Indexed arrays are typically written as a comma-separated value list, while associative arrays use key => value pairs. Elements are accessed and set with square-bracket notation; using an unassigned key with [] appends a new element with the next available integer index.
Cricket analogy: Writing [10, 4, 6, 0] is like listing a batter's last four scores in order, while ['Kohli' => 82, 'Rohit' => 45] pairs each player's name to their score directly; using [] with no key appends the next ball's result automatically to the over.
$fruits = ['apple', 'banana', 'cherry'];
$fruits[] = 'date'; // appended at index 3
$user = [
'name' => 'Grace',
'roles' => ['admin', 'editor'],
];
echo $fruits[0]; // apple
echo $user['roles'][1]; // editorIterating and Transforming Arrays
The foreach construct is the idiomatic way to iterate arrays, optionally destructuring keys with as $key => $value. PHP also provides list assignment ([$a, $b] = $array) for pulling positional or named values out of an array in one statement, which is especially handy when iterating a list of tuples or destructuring function return values. Because arrays preserve insertion order, iteration order is predictable unless the array has been explicitly sorted.
Cricket analogy: foreach iterating a scorecard is like reading each over in sequence, optionally as $over => $runs to get both the over number and runs scored; list assignment [$striker, $nonStriker] = $partnership pulls both batters out in one line, and insertion order keeps the innings chronological unless re-sorted.
$scores = ['Ada' => 98, 'Grace' => 95, 'Alan' => 90];
foreach ($scores as $name => $score) {
echo "$name scored $score\n";
}
$coordinates = [[0, 0], [3, 4], [6, 8]];
foreach ($coordinates as [$x, $y]) {
echo sqrt($x ** 2 + $y ** 2) . "\n"; // list destructuring
}Multidimensional and Mixed-Key Arrays
Arrays can contain other arrays as values, forming multidimensional structures that model trees, tables, or nested JSON-like data. Because keys can be any mix of integers and strings, the same array can behave like a record with named fields at one level and a numbered list at another. When merging arrays, array_merge() renumbers integer keys but preserves string keys (with later values overwriting earlier ones for the same string key), while the + operator preserves the left array's keys and integer indices entirely, only filling in keys missing from the left side.
Cricket analogy: A nested array like ['team' => 'India', 'players' => ['Kohli', 'Rohit']] models a squad sheet with named fields and a numbered player list at once; merging two squads with array_merge() renumbers the player list but keeps named fields like 'captain' intact, overwriting duplicates.
Because PHP arrays are ordered, you can rely on foreach visiting elements in the exact sequence they were inserted (or the sequence after an explicit sort) — unlike, for example, a plain Python dict before 3.7 or a Java HashMap, where order was historically unspecified.
array_merge($a, $b) and the + operator behave very differently for numeric keys: array_merge renumbers all integer keys sequentially, so numerically-keyed data can silently shift, while $a + $b keeps original keys and simply ignores duplicate keys from $b. Mixing them up is a common source of bugs when combining lists versus combining lookup tables.
- PHP has a single ordered array type that can be used as an indexed list, an associative map, or both at once.
- The short
[]syntax creates arrays;key => valuepairs define associative entries and$array[] = $valueappends. foreachis the idiomatic iteration construct and supports key/value destructuring as well as nested list destructuring.- Arrays preserve insertion order, so iteration order is predictable unless explicitly resorted.
array_merge()renumbers integer keys and lets later string keys overwrite earlier ones; the+operator preserves the left operand's keys.- Multidimensional arrays nest arrays as values to model tables, trees, or JSON-like records.
Practice what you learned
1. What happens when you use `$array[] = $value` on an array that has keys 0, 1, and 'name'?
2. How does `array_merge($a, $b)` treat integer keys shared between $a and $b?
3. What does the `+` (array union) operator do differently from array_merge()?
4. Which syntax correctly destructures the second element of each pair while iterating `[[1,2],[3,4]]`?
5. What guarantee does PHP make about iterating an array with foreach?
Was this page helpful?
You May Also Like
Array Functions
Survey PHP's extensive standard-library array functions for transforming, filtering, searching, and reducing arrays without manual loops.
String Functions and Formatting
Master PHP's core string manipulation and formatting functions, from searching and slicing to sprintf-style output and multibyte-safe operations.
Functions in PHP
Learn how PHP functions are declared, typed, and invoked, including default parameters, variadics, references, and closures for reusable logic.
Working with JSON in PHP
Learn how to encode PHP data to JSON and decode JSON back into PHP values using json_encode and json_decode, plus common pitfalls and error handling.
Related Reading
Related Study Notes in Programming
Browse all study notesApache Spark Study Notes
Programming · 30 topics
ProgrammingApache Flink Study Notes
Programming · 30 topics
ProgrammingHadoop Study Notes
Programming · 30 topics
ProgrammingSnowflake Study Notes
Programming · 30 topics
ProgrammingApache Airflow Study Notes
Programming · 30 topics
Programmingdbt (Data Build Tool) Study Notes
Programming · 30 topics