Advertisement
Google Ad Slot: content-top
PHP Associative Arrays
An associative array is an array where each element is stored with a custom key rather than a numeric index.
Example
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);
var_dump($person);
?>
Access Associative Arrays
Access elements using their keys:
Example
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);
echo $person["name"]."<br>"; // Outputs: Alice
echo $person["age"]; // Outputs: 30
?>
Change Value
Modify elements by reassigning a value to an existing key:
Example
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);
$person["age"] = 31; // Updates the value of "age" to 31
var_dump($person);
?>
Looping Through an Associative Array
You can loop through an associative array using a foreach loop:
Example
<?php
$person = array(
"name" => "Alice",
"age" => 30,
"city" => "New York"
);
foreach ($person as $key => $value) {
echo "$key: $value<br>";
}
?>