How to create a Table from a PHP array? (foreach)

Hi, is there a way to create a HTML table from array? Specifically ‘foreach’ function. I’d like a table with the heading ‘Element’ (for $key) and ‘Atomic Wg’ (for $value), thanks!

  $My_Array =  ["Sodium"=>22.990, "Lithium"=>6.940, "Chlorine"=>35.450, "Silicon"=>35.450, "Carbon"=>12.011, "Sulfur"=>32.060, "Oxygen"=>15.999, "Boron"=>10.810, "Neon"=>20.180, "Potassium"=>39.098, "Hydrogen"=>1.008, "Aluminium"=>26.982, "Phosphorus"=>30.974, "Fluorine"=>18.998, "Beryllium"=>9.012, "Argon"=>39.950, "Nitrogen"=>14.007, "Calcium"=>40.078,
     "Helium"=>4.003, "Magnesium"=>24.305];
  
 asort($My_Array);

    foreach ($My_Array as $key =>$value) 
    {
	echo "$key $value" . "<br>";
         }  

Hi @totallynotme !

Sure there is. PHP has the abiilty of embedding HTML within it, you use something like:

<?php

  $My_Array =  [
  "Sodium"=>22.990, 
  "Lithium"=>6.940,
  "Chlorine"=>35.450, 
  "Silicon"=>35.450, 
  "Carbon"=>12.011, 
  "Sulfur"=>32.060, 
  "Oxygen"=>15.999, 
  "Boron"=>10.810, 
  "Neon"=>20.180, 
  "Potassium"=>39.098, 
  "Hydrogen"=>1.008, 
  "Aluminium"=>26.982,  
  "Phosphorus"=>30.974, 
  "Fluorine"=>18.998, 
  "Beryllium"=>9.012, 
  "Argon"=>39.950, 
  "Nitrogen"=>14.007, 
  "Calcium"=>40.078,
  "Helium"=>4.003, 
  "Magnesium"=>24.305
];
  
 asort($My_Array);
?>
<html>
  <table>
<?php
foreach ($My_Array as $key =>$value) 
{
   ?><tr>
           <td><?php echo $key; ?></td>
           <td><?php echo $value; ?></td>
       </tr>
<?php
         }  
?>
  </table>
</html>

Cheers!

2 Likes

Hi, thanks for your reply, it works perfectly! Thank you so much :slight_smile:

No problem! Good luck :wink:

Sponsor our Newsletter | Privacy Policy | Terms of Service