Tuesday, January 26, 2016

PHP: foreach() loop

PHP: Circumference of planets table with alternating rows


$rad=array(
  'mercury' => 1516,
  'venus' => 3760,
  'earth' => 3959,
  'mars' => 2104,
  'jupiter' => 42982,
  'saturn' => 35615,
  'uranus' => 15700,
  'neptune' => 15256,
);

echo "<table border='1' width='300' >";
echo "<tr><td>Planet</td><td>Radius (mi)</td><td>Circumference (mi)</td></tr>";
foreach($rad as $key => $val){
  $cir=(2*M_PI)*$rad[$key];
  if($key == 'venus' || $key == 'mars' || $key == 'saturn' || $key == 'neptune'){
      echo "<tr><td><b>";
      printf("%s", $key);
      echo "</b></td>";
      echo "<td><b>";
      printf("%.2f", $val);
       echo "</b></td>";
     echo "<td><b>";
      printf("%.2f",$cir);
      echo "</b></td></tr>";
     
   }
  else{
      echo "<tr><td>";
      printf("%s", $key);
      echo "</td>";
      echo "<td>";
      printf("%.2f", $val);
      echo "</td>";
      echo "<td>";
      printf("%.2f",$cir);
      echo "</td></tr>";
     
    }

}

echo "</table>";




//Result

PlanetRadius (mi)Circumference (mi)
mercury1516.009525.31
venus3760.0023624.78
earth3959.0024875.13
mars2104.0013219.82
jupiter42982.00270063.87
saturn35615.00223775.64
uranus15700.0098646.01
neptune15256.0095856.28

No comments:

Post a Comment