[PHP] associative array and foreach syntax

Sep 9, 2020 PHP associative array for beginners foreach

About associative arrays

For example, if you have the following array

$ fruits = ['apple','lemon','banana'];

In the array stored in this variable $ fruits If you want to take out the apple, write as follows

print ($ fruits [0]);

I was able to retrieve it with this, but it is meaningless unless I remember the subscripts corresponding to each value. In such a case, use associative array It is often used for arrays where the order does not matter.

The above array is made into an associative array as follows.

$ fruits = [
  'apple' =>'apple',
  'lemon' =>'lemon',
  'banana' =>'banana'

At this time, the part on the left side of => ('apple') is called the key, and the part on the right side ('apple') is called the value.

In the associative array, if you want to take out the apple as before, write as follows

print ($ fruits ['apple']);

About foreach

foreach is an array-only syntax The contents of the array can be retrieved repeatedly.

To retrieve the contents (values only) of $ fruits from earlier with foreach, write as follows.

foreach ($ fruits as $ fruit) {
  print ($ fruit. "\ n");

(Line breaks as "\ n" for readability) When described in this way, the display is as follows.


In the above example, only the value is fetched, but in the associative array, you may want to fetch the key as well. In such a case, it may be described as follows.

foreach ($ fruits as $ fruit => $ katakana) {
  print ($ fruit. ":". $ Katakana. "\ n");

The display is as follows

apple: apple
lemon: lemon
banana: banana

The part of $ fruit => $ katakana is 'apple' =>'apple' 'lemon' =>'lemon' 'banana' =>'banana' It corresponds to ~

that’s all. Thank you for your hard work.