PHP Arrays: Indexed, Associative, and Multidimensional

Last updated: August 27, 2026.

A PHP array is an ordered map: each value has an integer or string key. The same structure can represent a list, lookup table, or nested collection.

Create and read an indexed array

<?php
$colors = ['red', 'green', 'blue'];

$colors[] = 'orange';
echo $colors[1]; // green
?>

Indexed arrays normally begin at key 0. Appending with [] uses the next available integer key.

Use meaningful keys

<?php
$product = [
    'name' => 'Mechanical keyboard',
    'price' => 89.95,
    'in_stock' => true,
];

echo $product['name'];
?>

Loop through keys and values

<?php
$stock = [
    'keyboard' => 12,
    'mouse' => 30,
    'monitor' => 8,
];

foreach ($stock as $item => $quantity) {
    echo htmlspecialchars($item) . ': ' . $quantity . PHP_EOL;
}
?>

Nested arrays

<?php
$orders = [
    ['id' => 1001, 'total' => 45.50],
    ['id' => 1002, 'total' => 72.00],
];

echo $orders[1]['total']; // 72
?>

Check optional keys with array_key_exists() or the null-coalescing operator before using them. See the PHP array documentation.

admin

admin

Leave a Reply

Your email address will not be published.