Advertisement

Google Ad Slot: content-top

PHP Associative Arrays

~1 min read · PHP
On this page

An associative array is an array where each element is stored with a custom key rather than a numeric index.

Example
"Alice", "age" => 30, "city" => "New York" ); var_dump($person); ?>
Try it yourself

Access Associative Arrays


Access elements using their keys:

Example
"Alice", "age" => 30, "city" => "New York" ); echo $person["name"]."
"; // Outputs: Alice echo $person["age"]; // Outputs: 30 ?>
Try it yourself

Change Value


Modify elements by reassigning a value to an existing key:

Example
"Alice", "age" => 30, "city" => "New York" ); $person["age"] = 31; // Updates the value of "age" to 31 var_dump($person); ?>
Try it yourself

Looping Through an Associative Array


You can loop through an associative array using a foreach loop:

Example
"Alice", "age" => 30, "city" => "New York" ); foreach ($person as $key => $value) { echo "$key: $value
"; } ?>
Try it yourself