Associative Arrays
In PHP, arrays are an essential type of data structure that stores one or more values in a single variable. One such type of array is the 'Associative Array'.
What are Associative Arrays?
Associative arrays are arrays that use named keys that you assign to them, unlike indexed arrays that use automatically assigned indexes. In other words, an associative array, in PHP, is actually an ordered map. A map is a type that associates values to keys.
Syntax
Here is the simple syntax to create an associative array:
$arrayName = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3"
);
In the above syntax, "key1" => "value1"
means that the array $arrayName
has a value "value1" associated with the key "key1".
Creating an Associative Array
Let's create a simple associative array that stores the ages of three people:
$ages = array(
"Peter" => "35",
"Ben" => "37",
"Joe" => "43"
);
In the above example, "Peter", "Ben", and "Joe" are the keys, and "35", "37", and "43" are the values associated with these keys.
Accessing Values in an Associative Array
To access the values from an associative array, you can use the keys. Here is an example:
echo "Peter is " . $ages['Peter'] . " years old.";
This will output: "Peter is 35 years old."
Looping Through an Associative Array
You can use a foreach
loop to loop through an associative array:
foreach($ages as $name => $age) {
echo "$name is $age years old.<br>";
}
This will output:
Peter is 35 years old.
Ben is 37 years old.
Joe is 43 years old.
In the foreach
loop, $name
and $age
are the key and value pair from the $ages
array for each iteration.
Modifying Values in an Associative Array
You can modify the value associated with a particular key in an associative array in the following way:
$ages['Peter'] = "36";
Now, if you echo the value of 'Peter', it will output '36'.
Conclusion
Associative arrays are a fundamental part of PHP and are immensely useful whenever you want to create a list with named keys instead of numeric indexes. By now, you should have a good understanding of how to create, access, loop through, and modify associative arrays in PHP. Keep practicing and experimenting with associative arrays as they are extensively used in PHP programming.