PHP Associative Arrays
In PHP, associative arrays are a powerful tool for storing and organizing data in a flexible way. They differ from traditional numerical arrays in how they use keys to access elements.
Example
<!DOCTYPE html> <html> <body> <pre> <?php $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); var_dump($car); ?> </pre> </body> </html>
Output
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}
• Access Associative Arrays
Associative arrays, also known as hash tables or dictionaries, are data structures that store key-value pairs. You can access elements using their unique keys, unlike indexed arrays where positions (indices) determine access.
Example
Display the model of the car:
<!DOCTYPE html> <html> <body> <?php $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); echo $car["model"]; ?> </body> </html>
Output
Mustang
• Change Value
To change the value of an array item, use the key name:
Example
Change the year item:
<!DOCTYPE html> <html> <body> <pre> <?php $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); $car["year"] = 2024; var_dump($car); ?> </pre> </body> </html>
Output
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(2024)
}
• Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use a foreach loop, like this:
Example
Display all array items, keys and values:
<!DOCTYPE html> <html> <body> <?php $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964); foreach ($car as $x => $y) { echo "$x: $y
"; } ?> </body> </html>
Output
brand: Ford
model: Mustang
year: 1964