$students = array( 'rishab' => array( 'age' =>25 , 'marks' =>400, 'class' =>'MCA' ), 'kamran' => array( 'age' =>23 , 'marks' =>550, 'class' =>'MBA' ), 'Sunil' => array( 'age' =>23 , 'marks' =>550, 'class' =>'MBA' ) );
how can i loop through this php associative array using foreach loop??
Advertisement
Answer
You can make a double foreach to loop all values of all sub arrays.
foreach($students as $key => $value) { echo 'Key: '.$key.'<br />'; foreach($value as $s_key => $s_value) { echo 'Sub key: '.$s_key.' => '.$s_value.'<br />'; } echo '<br />'; }
Result:
Key: rishab Sub key: age => 25 Sub key: marks => 400 Sub key: class => MCA Key: kamran Sub key: age => 23 Sub key: marks => 550 Sub key: class => MBA Key: Sunil Sub key: age => 23 Sub key: marks => 550 Sub key: class => MBA