Skip to content
Advertisement

Print Multi-dimensional array using loop in PHP

I don’t understand how to use nested loops(for, foreach,while,dowhile) for printing this multi-dimensional array values in separate lines. I am new in this sector.

Here is the code:

    <?php

$bazar = ['vegetables' => ['potato'=>16, 'cucumber'=>40, 'pumpkin'=>30, 'carrot'=>60], 

          'fruit' => ['apples'=> 150, 'pine-apple'=> '50', 'milk' => 100], 

          'fishes' => ['rui'=> 220, 'tuna' => 280, 'shrimp'=> 'it is delicious']
         ];





echo "<pre>";

print_r($bazar);

echo "</pre>";



foreach ($bazar as $net => $values) 
{
  echo $net."<br>";
};

?>

Advertisement

Answer

you have associative array inside associative array You have to loop the first associative array and inside it loop the associative array like this

foreach($bazar as $key => $val){

  echo $key.'<br>';
  
  foreach($val as $k => $v){
    echo $k . ' -> ' .$v . '<br>';
  }

}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement