Understanding Associative Arrays
Associative arrays (also called maps, dictionaries, or hash tables in other languages) use named keys instead of numeric indexes. Each key is associated with a value, creating key-value pairs that make data more meaningful and accessible.
Note: In PHP, there is no distinction between indexed and associative arrays at the implementation level - they're both the same data structure. This makes PHP arrays incredibly flexible.
Creating Associative Arrays
Create associative arrays by specifying keys explicitly:
<?php
// Method 1: Using array() function
$person = array(
"name" => "John Doe",
"age" => 30,
"city" => "New York"
);
// Method 2: Using short syntax (recommended)
$user = [
"username" => "johndoe",
"email" => "john@example.com",
"role" => "admin"
];
// Method 3: Adding elements one by one
$product = [];
$product["name"] = "Laptop";
$product["price"] = 999.99;
$product["stock"] = 50;
print_r($person);
print_r($user);
?>
Tip: Use descriptive key names that clearly indicate what data they represent. This makes your code self-documenting.
Accessing Array Elements
Access values using their keys instead of numeric indexes:
<?php
$book = [
"title" => "The Great Gatsby",
"author" => "F. Scott Fitzgerald",
"year" => 1925,
"genre" => "Fiction"
];
// Access individual elements
echo $book["title"]; // Output: The Great Gatsby
echo $book["year"]; // Output: 1925
// Check if key exists
if (isset($book["isbn"])) {
echo $book["isbn"];
} else {
echo "ISBN not available";
}
// Check if key exists (alternative)
if (array_key_exists("author", $book)) {
echo "Author: " . $book["author"];
}
?>
Warning: Always check if a key exists before accessing it to avoid "Undefined array key" warnings. Use isset() or array_key_exists().
Modifying and Adding Elements
You can modify existing values or add new key-value pairs:
<?php
$car = [
"brand" => "Toyota",
"model" => "Camry",
"year" => 2020
];
// Modify existing element
$car["year"] = 2022;
// Add new element
$car["color"] = "Blue";
$car["mileage"] = 15000;
print_r($car);
/*
Array (
[brand] => Toyota
[model] => Camry
[year] => 2022
[color] => Blue
[mileage] => 15000
)
*/
?>
Looping Through Associative Arrays
Use foreach to iterate over key-value pairs:
<?php
$student = [
"name" => "Alice Johnson",
"student_id" => "S12345",
"major" => "Computer Science",
"gpa" => 3.8
];
// Loop through values only
foreach ($student as $value) {
echo "$value<br>";
}
// Loop through keys and values (most common)
foreach ($student as $key => $value) {
echo "$key: $value<br>";
}
// Output:
// name: Alice Johnson
// student_id: S12345
// major: Computer Science
// gpa: 3.8
?>
Useful Array Functions
PHP provides many functions specifically for working with associative arrays:
<?php
$config = [
"host" => "localhost",
"port" => 3306,
"database" => "mydb",
"username" => "root"
];
// Get all keys
$keys = array_keys($config);
print_r($keys); // ["host", "port", "database", "username"]
// Get all values
$values = array_values($config);
print_r($values); // ["localhost", 3306, "mydb", "root"]
// Count elements
echo count($config); // 4
// Check if key exists
if (array_key_exists("password", $config)) {
echo "Password is set";
} else {
echo "Password is not set";
}
// Remove an element
unset($config["port"]);
print_r($config);
?>
Nested Associative Arrays
Associative arrays can contain other arrays, creating complex data structures:
<?php
$company = [
"name" => "Tech Corp",
"founded" => 2010,
"employees" => [
[
"name" => "John Doe",
"position" => "CEO",
"salary" => 150000
],
[
"name" => "Jane Smith",
"position" => "CTO",
"salary" => 140000
]
],
"offices" => [
"headquarters" => [
"city" => "New York",
"address" => "123 Main St"
],
"branch" => [
"city" => "London",
"address" => "456 High St"
]
]
];
// Access nested elements
echo $company["employees"][0]["name"]; // John Doe
echo $company["offices"]["headquarters"]["city"]; // New York
// Loop through nested arrays
foreach ($company["employees"] as $employee) {
echo "{$employee['name']} - {$employee['position']}<br>";
}
?>
Tip: Use nested associative arrays to represent complex real-world data like API responses, configuration files, or database results.
Merging Arrays
Combine multiple associative arrays:
<?php
$defaults = [
"theme" => "light",
"language" => "en",
"timezone" => "UTC"
];
$userSettings = [
"theme" => "dark",
"notifications" => true
];
// Merge arrays (later values override earlier ones)
$settings = array_merge($defaults, $userSettings);
print_r($settings);
/*
Array (
[theme] => dark
[language] => en
[timezone] => UTC
[notifications] => 1
)
*/
// Using + operator (earlier values take precedence)
$settings2 = $userSettings + $defaults;
print_r($settings2);
/*
Array (
[theme] => dark
[notifications] => 1
[language] => en
[timezone] => UTC
)
*/
?>
Sorting Associative Arrays
PHP provides several functions to sort associative arrays:
<?php
$prices = [
"apple" => 1.5,
"banana" => 0.8,
"cherry" => 2.5,
"date" => 3.0
];
// Sort by value (ascending)
asort($prices);
print_r($prices);
// [banana => 0.8, apple => 1.5, cherry => 2.5, date => 3.0]
// Sort by value (descending)
arsort($prices);
print_r($prices);
// [date => 3.0, cherry => 2.5, apple => 1.5, banana => 0.8]
// Sort by key (ascending)
ksort($prices);
print_r($prices);
// [apple => 1.5, banana => 0.8, cherry => 2.5, date => 3.0]
// Sort by key (descending)
krsort($prices);
print_r($prices);
// [date => 3.0, cherry => 2.5, banana => 0.8, apple => 1.5]
?>
Note: Sorting functions modify the array in place and return boolean (true/false) to indicate success, not a new array.
Practical Example: Form Data Processing
<?php
// Simulating form submission data
$formData = [
"first_name" => "John",
"last_name" => "Doe",
"email" => "john@example.com",
"phone" => "",
"message" => "Hello!"
];
// Validate required fields
$required = ["first_name", "last_name", "email"];
$errors = [];
foreach ($required as $field) {
if (empty($formData[$field])) {
$errors[] = ucfirst(str_replace("_", " ", $field)) . " is required";
}
}
if (empty($errors)) {
echo "Form is valid!<br>";
// Process form data
foreach ($formData as $key => $value) {
if (!empty($value)) {
echo ucfirst(str_replace("_", " ", $key)) . ": $value<br>";
}
}
} else {
echo "Errors:<br>";
foreach ($errors as $error) {
echo "- $error<br>";
}
}
?>
Practical Example: Configuration Management
<?php
// Database configuration
$dbConfig = [
"development" => [
"host" => "localhost",
"database" => "dev_db",
"username" => "dev_user",
"password" => "dev_pass"
],
"production" => [
"host" => "prod.server.com",
"database" => "prod_db",
"username" => "prod_user",
"password" => "prod_pass"
]
];
// Select environment
$environment = "development";
$db = $dbConfig[$environment];
echo "Connecting to {$db['database']} at {$db['host']}<br>";
// Function to get config value with default
function getConfig($config, $key, $default = null) {
return $config[$key] ?? $default;
}
echo getConfig($db, "host"); // localhost
echo getConfig($db, "port", 3306); // 3306 (default)
?>
Exercise:
- Create an associative array representing a product with: name, price, category, stock, and ratings
- Add a new field "discount" and calculate the final price
- Create an array of 3 products and sort them by price
- Write a function that searches products by category
- Create a nested array representing a shopping cart with multiple products and calculate the total
Best Practices
- Use descriptive, meaningful key names
- Keep key naming consistent (snake_case or camelCase)
- Always check if keys exist before accessing them
- Use
array_key_exists() to check for keys with null values
- Use
isset() for general existence checks
- Document complex nested array structures
- Use the null coalescing operator
?? for default values
Common Use Cases
- Configuration files: Store application settings
- Database results: Represent rows with column names as keys
- API responses: Handle JSON data converted to arrays
- Form processing: Handle $_POST and $_GET data
- Session storage: Store user-specific data in $_SESSION
- Translation files: Map language keys to translated strings
Warning:
- Keys are case-sensitive: "Name" and "name" are different keys
- Keys must be strings or integers (not floats or booleans)
- Using variable keys requires curly braces:
$arr["{$key}"]
- Be careful with type juggling - numeric string keys behave differently
Summary
In this lesson, you learned:
- How to create and use associative arrays with named keys
- How to access, modify, and add key-value pairs
- How to loop through associative arrays
- Useful functions for working with keys and values
- How to work with nested associative arrays
- How to merge and sort associative arrays
- Practical examples of form processing and configuration management
Associative arrays are essential for organizing and managing structured data in PHP. They're used extensively in web development for handling forms, database results, API data, and more!