PHP Associative Array
Associative arrays in PHP are those arrays that allow storing key-value pairs. That is, they allow you to set your own keys.
The syntax is as follows: key, followed by
an arrow =>, and then value.
Let's create an array of days of the week as an example.
Using an associative array, you can make it so that
Monday has the key 1,
and not zero:
<?php
$a = [1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday', 4 => 'Thursday', 5 => 'Friday', 6 => 'Saturday', 7 => 'Sunday'];
echo $a[1]; // outputs 'Monday'
?>
Keys don't necessarily have to be numbers; they can also be strings. Let's create an array where the keys are employee names, and the elements are their salaries:
<?php
// Employee array:
$a = ['John' => 200, 'Mary' => 300, 'Nick' => 400];
?>
Let's find out Mary's salary:
<?php
$a = ['John' => 200, 'Mary' => 300, 'Nick' => 400];
echo $a['Mary']; // outputs 300
?>
Arrays with explicitly specified keys are called associative.
A Trick with Keys
When we created the associative array of days of the week, we had to assign all keys manually.
Actually, there is no need to assign keys to
all elements - it is enough to assign the key
1 only to the first element.
If the second element doesn't have a key, PHP will assign it automatically, and it will be the next one in sequence.
And the next number will be exactly
2, since the previous element had
the key 1 (it doesn't matter that we set it ourselves,
and not PHP automatically).
Let's adjust our array:
<?php
// Let's specify keys explicitly:
$a = [1 => 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
echo $a[3]; // outputs 'Wednesday'
?>
This trick is quite useful, use it.