0
0
PHPprogramming~5 mins

Associative array creation in PHP

Choose your learning style9 modes available
Introduction

An associative array lets you store data with named keys instead of numbers. It helps you find values by names, like a small dictionary.

When you want to store a list of items with labels, like a person's name and age.
When you need to group related data together with meaningful keys.
When you want to access data by a name instead of a number index.
When you want to organize settings or options with clear names.
When you want to return multiple named values from a function.
Syntax
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.

Examples
This creates an associative array with keys 'name', 'age', and 'city'.
PHP
<?php
$person = [
    "name" => "Alice",
    "age" => 30,
    "city" => "Paris"
];
?>
This creates an empty associative array with no keys or values.
PHP
<?php
$emptyArray = [];
?>
This creates an associative array with just one key-value pair.
PHP
<?php
$singleItem = ["color" => "blue"];
?>
Keys can also be numbers, not just strings.
PHP
<?php
$numbers = [1 => "one", 2 => "two", 3 => "three"];
?>
Sample Program

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
<?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);
?>
OutputSuccess
Important Notes

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.

Summary

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.