Quiz associative array

$a1 = [“Alex” => “Sara”, “Sara” => “Kat”, “Kat” => “Toshi”, “Dan” => “Dan”];
$a2 = [“Dan”, “Kat”, “Sara”, “Alex”, “Toshi”];
echo $a1[$a2[1]];

Can anyone explain to me why it echo “Toshi”?

I have tried to echo “$a1[1];” it returns " ``Undefined offset: 1", why is that?

I believe in PHP an associative array works like a dictionary works in python.
Basically, if an array is an associative array it doesn’t behave like a regular array in that you don’t access it by index number, you access it by key value.

So for example, for getting the values for $a1, you have to name the keys:

echo $a1[“Alex”]; // will access the key "Alex", which has a value of "Sara"
echo $a1[“Sara”]; // will access the key "Sara", which has a value of "Kat"
echo $a1[“Kat”]; // will access the key "Kat", which has a value of "Toshi"
echo $a1[“Dan”]; // will access the key "Dan", which has a value of "Dan"
// note, the above are the only keys

The given example is a bit messy as a starting example, a simpler example would be imagining how much money everyone has in their pocket

$a1 = [“Alex” => 5, “Sara” => 100, “Kat” => 20, “Dan” => 0];
echo $a1["Alex"]; // will give you 5

Now, it it just has one value it’s not too interesting, but I think you should be able to point to any object, like another array (which means you can pack many values in one key, for example for one person you can track their money, id#, age, etc. However I’m not 100% how this would be done in PHP but you should look into it as it’s a useful way to use associative arrays.

2 Likes

As @toastedpitabread mentioned, you are accessing $a1 by a key. Here, you gave it the value of $a2[1] as the key.

The value of $a2[1] is the string "Kat", and looking at $a1's key-value pairs, the value for the key "Kat" is "Toshi". This is much like Dictionaries in Python or Maps in other languages, so it’s definitely worth taking some time to understand it further.