In PHP, associative arrays are arrays that use named keys instead of numeric indexes. They are useful when you want to store data in a key-value pair format, similar to dictionaries in other languages.
Add custom keys and values to see how they are structured in an associative array.
Associative arrays are created using the => operator:
// Defining an associative array with key-value pairs
$arrayName = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);
// Creating an associative array and accessing a value
<?php
$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
echo "Peter is " . $age["Peter"] . " years old.";
?>
Peter is 35 years old.
// Looping through associative array using foreach
<?php
$age = array("Peter" => 35, "Ben" => 37, "Joe" => 43);
foreach ($age as $name => $value) {
echo "$name is $value years old.
";
}
?>
// Adding and removing elements in associative array
<?php
$age = array("Peter" => 35, "Ben" => 37);
$age["Joe"] = 43;
unset($age["Ben"]);
print_r($age);
?>
Array ( [Peter] => 35 [Joe] => 43 )
// Nested associative array for structured data
<?php
$contacts = array(
"Peter" => array("Phone" => "123456", "Email" => "peter@example.com"),
"Ben" => array("Phone" => "987654", "Email" => "ben@example.com")
);
echo $contacts["Peter"]["Email"];
?>
peter@example.com