0
0
PhpComparisonBeginner · 3 min read

Indexed vs Associative Array in PHP: Key Differences and Usage

In PHP, an 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.

FeatureIndexed ArrayAssociative Array
Key TypeNumeric (0, 1, 2, ...)String or custom keys
Default KeysAutomatically assigned starting at 0Must be explicitly set
Use CaseOrdered list of itemsKey-value pairs with named keys
Access MethodBy numeric indexBy named key
Example["apple", "banana"]["name" => "John", "age" => 30]
Iteration OrderPreserves insertion orderPreserves 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
<?php
$fruits = ["apple", "banana", "cherry"];
echo $fruits[1]; // Outputs: banana
?>
Output
banana
↔️

Associative Array Equivalent

Here is how you create and access an associative array in PHP:

php
<?php
$user = ["name" => "John", "age" => 30, "city" => "Paris"];
echo $user["name"]; // Outputs: John
?>
Output
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.

Key Takeaways

Indexed arrays use numeric keys and are best for ordered lists.
Associative arrays use named keys for meaningful key-value pairs.
Use indexed arrays for simple sequences and associative arrays for labeled data.
Both preserve the order of elements as inserted.
Access indexed arrays by number and associative arrays by key.