Associative arrays are arrays that use named keys that you assign to them. Instead of accessing items by number (0, 1, 2), you access them by a meaningful string (their key).
To create an associative array, you define the key and its associated value using the => operator.
<?php
$age = [
"Peter" => "35",
"Ben" => "37",
"Joe" => "43"
];
?>
Accessing data is as simple as putting the key name inside the square brackets. Note that keys are case-sensitive.
<?php
$age = ["Peter" => "35", "Ben" => "37"];
echo "Peter is " . $age['Peter'] . " years old.";
// Updating a value
$age['Peter'] = "36";
?>
The foreach loop is specifically designed to handle associative arrays. You can pull out both the name of the key and the data it holds in one go.
<?php
$user = [
"name" => "RedoHub",
"role" => "Admin",
"email"=> "info@redohub.com"
];
foreach($user as $key => $value) {
echo "The user's $key is: $value <br>";
}
?>