PHP Associative Arrays
Instead of numbering items, an associative array labels each one with a key you choose.
Example
Prompt
Write a PHP script that creates an associative array with keys "brand", "model", and "year" set to "Ford", "Mustang", and 1964, then displays it with var_dump().
Output: PHP script
index.php
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
var_dump($car);
?>
Access Array Item
Write the key name in the brackets to read one particular item.
Example
Print the car's model:
Prompt
Write a PHP script that creates an associative array for a car with brand "Ford", model "Mustang", and year 1964, then prints the model value.
Output: PHP script
index.php
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
echo $car["model"];
?>
Change Value of Array Item
Changing an item also goes through its key. Assign the new value to that key name:
Example
Set year to a new value:
Prompt
Write a PHP script that creates an associative array for a car with brand "Ford", model "Mustang", and year 1964, changes the year to 2024, then displays the array with var_dump().
Output: PHP script
index.php
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
$car["year"] = 2024;
var_dump($car);
?>
Loop Through an Associative Array
A foreach loop walks through the whole array, handing you each key and value so you can print them:
All the array functions are described in our PHP Array Reference.
Example
Print every key next to its value:
Prompt
Write a PHP script that creates an associative array for a car with brand "Ford", model "Mustang", and year 1964, then uses a foreach loop to print each key and value followed by an HTML line break.
Output: PHP script
index.php
<?php
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}
?>