An indexed array usually represents a list, such as three product names. An associative array uses meaningful keys, such as a product's name, price and stock count. PHP implements both with one array type: an ordered map from integer or string keys to values. Understanding that shared structure helps you avoid accidental key replacement and unexpected JSON output.
This detailed reference explains how to choose a shape, read and update values, iterate safely, and preserve identity while combining arrays. Start with PHP arrays if square brackets and foreach are new. The goal is to make each key's meaning clear, rather than treating every array as an interchangeable bag of values.
A list uses positions; a map uses names
A simple list written as ['Pen', 'Book'] receives keys zero and one. You use those positions when order defines meaning, or iterate without caring about individual positions. Appending with $items[] = 'Bag' adds a new entry using PHP's next integer-key rule. A list does not have to be sorted alphabetically to remain a list.
An associative record such as ['name' => 'Pen', 'stock' => 8] uses keys to describe fields. Read the name with $product['name']. Renaming a key changes the data contract, even if the value stays the same. A collection keyed by product identifier is also associative because the keys represent identity rather than display position.
Mixed keys are legal, but legality does not guarantee clarity. An array containing a product record and a numeric list item can become difficult to validate. Keep one understandable role per array: a list of records, a record with named fields, or a map indexed by identifier. Document required fields at the boundary where data enters the application.
Key conversions can cause collisions
Array keys are integers or strings. Some supplied keys are converted. A string containing a valid decimal integer, such as '8', is commonly stored as integer eight. A leading-zero string such as '08' remains a string. Boolean keys become zero or one, and null becomes an empty string. Avoid floats as keys because conversion loses the fractional part and modern PHP may report precision-loss diagnostics.
If two entries resolve to the same key, the later assignment replaces the earlier value. You do not receive two separately stored items under that key. This is useful for intentional updates but dangerous when an identifier format is ambiguous. Normalize identifiers deliberately, or prefix external numeric-looking identifiers with a stable label when preserving their textual identity matters.
The array preserves insertion order, not a promise that keys are consecutive. Removing an item leaves a gap. Sorting with some functions resets numeric keys; other functions preserve them. Know whether your keys represent positions or identifiers before choosing an operation. The PHP array manual documents key conversion and version-sensitive append behavior.
Reading optional fields and iterating
Reading an absent key directly produces a warning in modern PHP. Use ?? for a documented fallback when missing and null should share a meaning. Use array_key_exists() when a null value must be distinguished from absence. Validate type after presence: an existing stock field can still contain invalid text or an array.
foreach ($items as $key => $value) exposes both parts. For a list, the key is commonly a position. For a map, it may be the identity you must retain when building another result. Avoid changing array structure unpredictably during iteration. Build a separate result when filtering or transforming records unless in-place mutation is a clear requirement.
Assigning an array normally has value semantics, with PHP optimizing storage through copy-on-write. However, objects inside the array remain references to object instances, and explicit references introduce additional sharing. Copying an array does not deep-clone every object it contains. Keep that distinction visible when arrays hold mutable domain objects.
Combining arrays and serializing them
array_merge() appends and renumbers numeric-keyed entries while later string-keyed entries replace earlier ones. The array union operator + keeps existing left-hand keys and adds only keys absent from the left. These are different merge policies. Use merge for concatenating ordinary lists; choose an explicit policy for maps where replacement order matters.
JSON encoding distinguishes a consecutive zero-based list from other PHP arrays. A list becomes a JSON array. A map, or numeric keys with gaps, becomes a JSON object. array_values() deliberately discards keys and creates a list. Do not call it on a map whose keys carry product identity merely to change the JSON appearance.
PHP 8.1 added array_is_list() for detecting zero-based consecutive integer keys. The empty array counts as a list. Detection does not validate the element types or required fields. A list of arbitrary values is still a list even when your endpoint expects a list of product records.
PHP Indexed vs Associative Arrays Examples
Each example shows the code, the output it produces and what each part does.
Compare a list and a record
The list's key two means the third position. The record's key stock means a specific field. Both values are arrays, but callers must know which shape they expect. Passing the list to code that expects a name field is a contract error, not a difference in PHP array types.
<?php
$names = ['Pen', 'Book'];
$names[] = 'Bag';
$product = ['name' => 'Pen', 'stock' => 8];
echo $names[2] . PHP_EOL;
echo $product['name'] . ':' . $product['stock'] . PHP_EOL;Bag
Pen:8PHP Indexed vs Associative Arrays in Real Projects
Practical task: keep product identifiers
Given a map from product identifiers to stock counts, build a second map containing only products with positive stock. Preserve the identifiers so a caller can look up a product without interpreting a display position. Use an explicit condition that keeps the keys rather than reindexing the result.
<?php
$stock = ['pen' => 3, 'book' => 0, 'bag' => 2];
$available = [];
foreach ($stock as $id => $quantity) {
if ($quantity > 0) {
$available[$id] = $quantity;
}
}
echo json_encode($available, JSON_THROW_ON_ERROR) . PHP_EOL;{"pen":3,"bag":2}The object-shaped JSON is intentional because pen and bag are identities. A separate product-name list would instead use $available[] and produce JSON array output. Try using integer product identifiers and explain why reindexing would lose the mapping. In real input, validate quantities as bounded nonnegative integers before comparing them.
PHP Indexed vs Associative Arrays FAQ
Are indexed and associative arrays different PHP types?
No. Both use PHP's ordered-map array type. The names describe common shapes and usage.
Does deleting an element renumber a list?
No. Use array_values only when you intentionally want consecutive positions afterward.
Why did two numeric-looking keys overwrite each other?
Their key conversion may have produced the same integer key. Inspect the stored keys and define an unambiguous identifier policy.
Does count give the largest index?
No. It counts entries. An array with keys zero and ninety can contain only two entries.
When should I use an object instead?
A typed object can better represent a record with behavior and stable fields. Arrays remain useful for simple lists, maps and external data boundaries.
PHP Indexed vs Associative Arrays Exercises
Answer each one and check it instantly. If you get stuck, open the hint before the answer.
Product IDs must remain attached to stock counts. Which result assignment preserves them?
PHP Indexed vs Associative Arrays Quiz
2 questions to check what you learned.
What key does the first item in ['Pen', 'Book'] normally receive?
- 1
- 'first'
- 0
Which operation deliberately discards keys and creates a zero-based list?
- array_values()
- array_keys()
- array_key_exists()