Google News
logo
PHP Program to Associative arrays
In the following example of PHP program that demonstrates how to create and work with associative arrays :
Program :
<?php

// Create an associative array
$ages = array("John" => 25, "Mary" => 30, "Bob" => 35);

// Access and print the values of the array
echo "John is " . $ages["John"] . " years old.<br>";
echo "Mary is " . $ages["Mary"] . " years old.<br>";
echo "Bob is " . $ages["Bob"] . " years old.<br>";

// Add a new element to the array
$ages["Jane"] = 28;

// Access and print the updated values of the array
echo "Jane is " . $ages["Jane"] . " years old.<br>";

?>
Output :
John is 25 years old.
Mary is 30 years old.
Bob is 35 years old.
Jane is 28 years old.
In this example, we have created an associative array `$ages` using the `array()` function with three elements, each with a key-value pair. We access and print the values of the array using the key names "John", "Mary", and "Bob".

We then add a new element "Jane" to the array with a value of `28` using the `$ages["Jane"]` syntax. We access and print the updated values of the array using the key name "Jane".

Associative arrays are similar to indexed arrays, but instead of using numeric index numbers, they use keys to identify the elements. This allows us to store and access data in a more descriptive and organized way.