Indexed vs Associative Array in PHP: Key Differences and Usage
indexed array uses numeric keys starting from 0 by default, while an associative array uses named keys (strings) to access values. Indexed arrays are like lists, and associative arrays are like dictionaries with key-value pairs.Quick Comparison
Here is a quick side-by-side comparison of indexed and associative arrays in PHP.
| Feature | Indexed Array | Associative Array |
|---|---|---|
| Key Type | Numeric (0, 1, 2, ...) | String or custom keys |
| Default Keys | Automatically assigned starting at 0 | Must be explicitly set |
| Use Case | Ordered list of items | Key-value pairs with named keys |
| Access Method | By numeric index | By named key |
| Example | ["apple", "banana"] | ["name" => "John", "age" => 30] |
| Iteration Order | Preserves insertion order | Preserves insertion order |
Key Differences
An indexed array in PHP is a simple list where each element is accessed by a numeric index starting at 0. PHP automatically assigns these numeric keys if you don't specify them. This makes indexed arrays ideal for ordered collections like lists of items or numbers.
On the other hand, an associative array uses named keys, which are usually strings, to access values. You define these keys yourself, making associative arrays perfect for storing data with meaningful labels, like user information or settings.
Both types preserve the order of elements as they were added, but their main difference lies in how you access the data: numeric indexes for indexed arrays and named keys for associative arrays.
Code Comparison
Here is how you create and access an indexed array in PHP:
<?php $fruits = ["apple", "banana", "cherry"]; echo $fruits[1]; // Outputs: banana ?>
Associative Array Equivalent
Here is how you create and access an associative array in PHP:
<?php $user = ["name" => "John", "age" => 30, "city" => "Paris"]; echo $user["name"]; // Outputs: John ?>
When to Use Which
Choose an indexed array when you need a simple list of items accessed by position, like a list of colors or numbers. Use an associative array when you want to label each item with a meaningful key, such as storing user details or configuration settings. Associative arrays make your code more readable when keys describe the data.