An associative array lets you store data with named keys instead of numbers. It helps you find values by names, like a small dictionary.
Associative array creation in PHP
<?php
$associativeArray = [
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
];
?>Keys are usually strings but can also be integers.
Use the => symbol to assign a value to a key.
<?php
$person = [
"name" => "Alice",
"age" => 30,
"city" => "Paris"
];
?><?php $emptyArray = []; ?>
<?php $singleItem = ["color" => "blue"]; ?>
<?php $numbers = [1 => "one", 2 => "two", 3 => "three"]; ?>
This program creates an associative array for a car with make, model, and year. It prints the array, adds a new key 'color', then prints the updated array.
<?php // Create an associative array with some data $car = [ "make" => "Toyota", "model" => "Corolla", "year" => 2020 ]; // Print the array before adding a new item print_r($car); // Add a new key-value pair $car["color"] = "red"; // Print the array after adding the new item print_r($car); ?>
Accessing a value by key is very fast, usually O(1) time.
Associative arrays use more memory than simple indexed arrays because they store keys.
Common mistake: forgetting quotes around string keys can cause errors.
Use associative arrays when you want to label data clearly; use indexed arrays when order matters more than names.
Associative arrays store data with named keys for easy access.
Use the => symbol to assign values to keys inside square brackets.
They are great for grouping related data with meaningful names.