Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get key of multidimensional array in foreach loop using php? [duplicate]

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?

like image 786
JohnSnow Avatar asked Feb 19 '17 18:02

JohnSnow


1 Answers

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

like image 59
Mohammad Avatar answered Nov 07 '22 14:11

Mohammad