An associative array is a type of array that stores a collection of values that are accessed using string keys. The keys are used to identify the elements, and can be any string value. Associative arrays are useful for storing and accessing data that is more complex and structured than simple lists of values. They are often used to store data that has an inherent meaning, such as the data for a person object (e.g. name, age, gender) or a product object (e.g. name, price, quantity).
Here is an example of an associative array in PHP:
$person = array('name' => 'John', 'age' => 30, 'gender' => 'male');
echo $person['name']; // Outputs "John"
echo $person['age']; // Outputs "30"
echo $person['gender']; // Outputs "male"
In this example, the $person
array has three elements with keys ‘name’, ‘age’, and ‘gender’. The elements can be accessed using the array keys in square brackets.
You can also create an associative array using the array
function:
$person = array('name' => 'John', 'age' => 30, 'gender' => 'male');
// or
$person = array();
$person['name'] = 'John';
$person['age'] = 30;
$person['gender'] = 'male';
Once you have declared an associative array, you can access and manipulate the elements using the array keys. For example:
echo $person['name']; // Outputs "John"
echo $person['age']; // Outputs "30"
echo $person['gender']; // Outputs "male"
$person['name'] = 'Jane';
echo $person['name']; // Outputs "Jane"
In these examples, the elements of the $person
array are accessed and modified using the array keys in square brackets.
You can also use the various array functions in PHP to manipulate associative arrays, such as count()
to count the elements, array_keys()
to get the keys of the elements, and array_values()
to get the values of the elements.