Associative Arrays in PHP
Consider the following array, storing parts of a date:
<?php
$arr = [2025, 12, 31];
?>
As you already know, to get an element from this array, we need to access it by its index number. However, this is not always convenient.
Therefore, PHP allows you to set your own keys for array elements. Such an array will be called associative.
Associative arrays have the following syntax: key name,
followed by an arrow =>
, and then
the value. Let's specify explicit keys for
our array:
<?php
$arr = [
'year' => 2025,
'month' => 12,
'day' => 31
];
?>
Now we will access the elements of our array using the keys we defined. Let's do it:
<?php
echo $arr['year']; // will output 2025
echo $arr['month']; // will output 12
echo $arr['day']; // will output 31
?>
Create an array $user
with keys 'name'
,
'surname'
, 'patronymic'
and some
arbitrary values. Output to the screen
the surname, name, and patronymic separated by a space.
Create an array with keys from 1
to 7
, containing the
names of the days of the week as values. Output to the screen
all its elements.