5

I need to print the student name and the mark from the following array for a given subject:

$marks = [
    "john" => ["physics" => 30, "maths" => 55, "chemistry" => 66],
    "jack" => ["physics" => 44, "maths" => 19, "chemistry" => 87],
    "mark" => ["physics" => 77, "maths" => 66, "chemistry" => 67],
];

I understand that if I do echo $marks['john']['chemistry']; it will print the mark for the student/subject, but how should I approach a foreach loop for displaying all students and their scores for chemistry?

Mohammad
  • 21,175
  • 15
  • 55
  • 84
JohnSnow
  • 163
  • 4
  • 16

1 Answers1

5

In php foreach() you can get key of current item like this

foreach ($array as $key=>$item){...}

Also use it like bottom code

foreach ($marks as $name=>$scores){
    echo $name .":". $scores["chemistry"];
}

See result of code in demo

Mohammad
  • 21,175
  • 15
  • 55
  • 84
  • This was an eye opener for me. I'd always use: foreach $array as $key => $value for a single dimension array but used: foreach $multiarray as $array.. and didn't stop to think you could get $key => $array in the second case. Excellent, thanks. – cdsaenz Oct 06 '20 at 19:04