0
$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??

1

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

what if query return id and name how to loop through so the id and name can settle in one <td value = "id">name</td>
0
foreach( $students as $name=>$student){
    print $name . ":" . $student["class"] . PHP_EOL;
}

will output this

rishab:MCA
kamran:MBA
Sunil:MBA

2 Comments

what if query return id and name how to loop through so the id and name can settle in one <td value = "id">name</td>
what if query return id and name how to loop through so the id and name can settle in one <td value = "id">name</td>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.