PHP Associative Arrays

In PHP, associative arrays are arrays that use named keys (strings) instead of numerical indexes to store values. They're similar to dictionaries or hash maps in other languages.

Basic Syntax

$person = array( "first_name" => "John", "last_name" => "Doe", "age" => 30 );

Or using the short array syntax (PHP 5.4+):

$person = [ "first_name" => "John", "last_name" => "Doe", "age" => 30 ];

Accessing Values

echo $person["first_name"]; // Outputs: John

Adding or Updating Elements

$person["gender"] = "male"; // Adds a new key-value pair $person["age"] = 31; // Updates the existing value

Looping Through Associative Arrays

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

Checking if a Key Exists

if (array_key_exists("age", $person)) { echo "Age is set."; }

Removing an Element

unset($person["age"]);