PHP Associative Array
An associative array is an array that uses named keys to assign values to them. Unlike indexed arrays, associative arrays allow you to use meaningful keys instead of numeric keys.
Syntax
$arrayname = array(
"key1" => "value1",
"key2" => "value2",
"key3" => "value3",
...
);
Example
$students = array(
"John" => 25,
"Mary" => 28,
"Peter" => 30
);
Output
Array
(
[John] => 25
[Mary] => 28
[Peter] => 30
)
Explanation
In the above example, we have created an associative array named $students
. The keys of this array are the names of the students and the values are their respective ages.
Use
Associative arrays can be used to store data in a structured way where each value can be accessed using a meaningful key. They are especially useful when working with large datasets where you need to retrieve specific values quickly.
Important Points
Associative arrays in PHP are considered as maps, hash maps, dictionaries or simply as objects.
The keys in an associative array must be unique.
You can add, modify, or delete elements of an associative array using the
=
sign.You can use the
foreach
loop to loop through the associative array.
Summary
Associative arrays are a powerful feature of PHP that allows you to create arrays based on meaningful keys. You can use them to store and retrieve data quickly and efficiently. Remember that the keys in an associative array must be unique and that you can use the foreach
loop to loop through the elements of the array.