Accessing array elements within an array in php
Multidimensional arrays often contains arrays within arrays instead of single matrix elements form. We can access inside elements in 2 dimensional form as :
Example
<!DOCTYPE html> <html> <head> <title>Accessing array elements within an array</title> </head> <body> <?php $marks = array( "Person1" => array ( "physics" => 35, "maths" => 30, "chemistry" => 39 ), "Person2" => array ( "physics" => 30, "maths" => 32, "chemistry" => 29 ), "Person3" => array ( "physics" => 31, "maths" => 22, "chemistry" => 39 ) ); /* Accessing multi-dimensional array values */ echo "Marks for person 1 in physics is : " . $marks['Person1']['physics'] . "<br>"; echo "Marks for person 3 in chemistry is : " . $marks['Person3']['chemistry'] . "<br>"; // ITERATING ALL IN A FOREACH LOOP foreach($marks as $sub_array) { echo $sub_array['physics'] ." ". $sub_array['maths'] . " " . $sub_array['chemistry'] . "<br>"; } ?> </body> </html>
Output
Marks for person 1 in physics is : 35
Marks for person 3 in chemistry is : 39
35 30 39
30 32 29
31 22 39