QA
Beginner LevelPHP 8+

What is the difference between Indexed, Associative, and Multidimensional Arrays in PHP?

❓ Interview Prompt: Explain PHP array structure, integer keys vs string keys, and how PHP arrays are internally implemented as ordered hash tables.

Unlike languages like C or Java that have separate data structures for indexed arrays, linked lists, and dictionaries/hash maps, PHP has only one underlying array type: an Ordered Hash Table.

1. Indexed Arrays:

•
Arrays where keys are sequential numeric integers starting at '0'.
•
Syntax: '$fruits = ["Apple", "Banana", "Cherry"];'

2. Associative Arrays:

•
Arrays where keys are named strings (acting like dictionaries or hash maps in Python/JS).
•
Syntax: '$user = ["name" => "Alice", "role" => "admin", "age" => 28];'

3. Multidimensional Arrays:

•
Arrays containing nested arrays as values, used to represent grids or tabular database query results.
•
Syntax: '$users = [ ["id" => 1, "name" => "Alice"], ["id" => 2, "name" => "Bob"] ];'

Because PHP arrays are ordered hash maps, they preserve the exact insertion order of elements when looped over with 'foreach', regardless of whether keys are integers or strings!

Code Implementation Example

php
<?php
// 1. Indexed Array (numeric keys 0, 1, 2)
$colors = ['Red', 'Green', 'Blue'];
echo $colors[0]; // Outputs: Red

// 2. Associative Array (string keys)
$product = [
    'sku' => 'LAPTOP-99',
    'price' => 1299.99,
    'in_stock' => true
];
echo $product['sku']; // Outputs: LAPTOP-99

// 3. Looping over Associative Arrays with foreach
foreach ($product as $key => $value) {
    echo "{$key}: {$value}
";
}

// 4. Modifying nested Multidimensional Arrays
$cart = [
    ['item' => 'Book', 'qty' => 2],
    ['item' => 'Pen', 'qty' => 5]
];
$cart[0]['qty'] = 3; // Updates Book quantity to 3
💡Syntax and foreach traversal of indexed, associative, and multidimensional PHP arrays.
🎯 Interview Key Takeaway

PHP arrays are ordered hash tables supporting both sequential integer keys (indexed) and named string keys (associative).

#Arrays#Associative Arrays#Hash Tables#Beginner
Back to all PHP 8+ Questions→

More PHP 8+ Interview Questions

Beginner LevelPHP

What is PHP and how does its shared-nothing request lifecycle work?

Beginner LevelPHP

What is the difference between echo and print in PHP?

Beginner LevelPHP

What is the difference between isset(), empty(), and is_null() in PHP?