In PHP, an associative array is a data structure 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.
There are two ways to declare an associative array in PHP: using the array
function, or using the literal syntax.
Using the array
function:
$array = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3');
// or
$array = array();
$array['key1'] = 'value1';
$array['key2'] = 'value2';
$array['key3'] = 'value3';
In these examples, the array
function is used to create an associative array. The keys are specified as string values in the first example, and are added using the assignment operator in the second example.
Using the literal syntax:
$array = ['key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3'];
In this example, the literal syntax is used to create an associative array. The keys are specified as string values in square brackets. This syntax is available in PHP version 5.4 and higher.
Once you have declared an associative array, you can access and manipulate the elements using the array keys. For example:
echo $array['key1']; // Outputs "value1"
echo $array['key2']; // Outputs "value2"
echo $array['key3']; // Outputs "value3"
$array['key1'] = 'new value';
echo $array['key1']; // Outputs "new value"
In these examples, the elements of the $array
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.
Here is an example of using some of these functions with an associative array:
echo count($array); // Outputs 3
print_r(array_keys($array)); // Outputs array('key1', 'key2', 'key3')
print_r(array_values($array)); // Outputs array('new value', 'value2', 'value3')