Skip to content

Working with Associative Arrays in PHP

Here’s a breakdown of the structure and usage of associative arrays in PHP:

  1. Keys: These are identifiers for the array elements. In associative arrays, keys are typically strings but can also be integers.
  2. Values: These are the data elements stored in the array and can be of any data type (e.g., strings, integers, arrays, objects, etc.).

You can create an associative array using the array() function or the shorthand syntax.

Here’s how you can define and initialize an associative array:

// Using array() function
$person_info = array(
"name" => "John",
"age" => 25,
"city" => "laval"
);
// Using shorthand syntax (PHP 5.4+)
$person_info = [
"name" => "John",
"age" => 25,
"city" => "laval"
];

To access the elements of an associative array, use the key inside square brackets:

echo $person_info["name"]; // Outputs: John
echo $person_info["age"]; // Outputs: 25
echo $person_info["city"]; // Outputs: laval

You can also modify the value associated with a specific key:

$person_info["age"] = 26;
echo $person_info["age"]; // Outputs: 26

To add a new key-value pair to the associative array:

$person_info["country"] = "USA";
echo $person_info["country"]; // Outputs: USA

You can use the isset() function to check if a key exists in the associative array:

if (isset($person_info["city"])) {
echo "City is set!";
} else {
echo "City is not set!";
}

To remove an element from the associative array, use the unset() function:

unset($person_info["city"]);

After removing the “city” key, accessing $person_info["city"] would produce an undefined index notice.

You can use a foreach loop to iterate over an associative array:

foreach ($person_info as $key => $value) {
echo "$key: $value <br>";
}

This will output each key-value pair in the associative array.

Here’s a complete example demonstrating how to manipulate associative arrays in PHP:
<?php
// Creating an associative array
$person = [
"name" => "Alice",
"age" => 30,
"city" => "Montreal"
];
// Accessing elements
echo $person["name"] . " <br>"; // Outputs: Alice
// Modifying elements
$person["age"] = 31;
echo $person["age"] . " <br>"; // Outputs: 31
// Adding a new element
$person["job"] = "Engineer";
// Checking if a key exists
if (isset($person["city"])) {
echo "City is set to " . $person["city"] . " <br>"; // Outputs: City is set to Montreal
}
// Removing an element
unset($person["city"]);
// Iterating over the array
foreach ($person as $key => $value) {
echo "$key: $value <br>";
}
?>

This will output:

Alice
31
City is set to Montreal
name: Alice
age: 31
job: Engineer