I am creating a volume converter. It allows users to enter a value and select the unit to convert from and the one it will be converted into. It uses a <select> tag for user input selection.

The <select> looks like this:

<select name="from">
  <option value=0>--select--</option>
  <option value=1>cm3</option>
  <option value=2>m3</option>
  <option value=3>Feet3</option>
  <option value=4>Gallons(UK)</option>
  <option value=5>Gallons(US)</option>
  <option value=6>Inches3</option>
  <option value=7>Litres</option>
  <option value=8>Yards3</option>
  <option value=9>Quart(UK)</option>

And there is another one similar to this with the name "to".

After that I did the following in PHP:


function assign($from,$val)
          switch ($from)
              case 1:
               case 2:

There are 7 more cases based on the html select "from" and each holds a value of conversion for each unit relative to the selection made.

It ends with:

        echo "<br><br><table align=center>
     <tr><td><h3> ",$val," ",$fromu," equivalent is </h3></td></tr>
     <tr align=right><td><u> ",(double)($val*$cm),"</u> CentiMeter<sup>3</sup></td></tr>
     <tr align=right><td><u> ",(double)($val*$me),"</u> Meter<sup>3</sup></td></tr>
     <tr align=right><td><u> ",(double)($val*$ft),"</u> Feet<sup>3</sup></td></tr>
     <tr align=right><td><u> ",(double)($val*$gk),"</u> Gallons(UK)</td></tr>
     <tr align=right><td><u> ",(double)($val*$gs),"</u> Gallons(US)</td></tr>
     <tr align=right><td><u> ",(double)($val*$in),"</u> Inches<sup>3</sup></td></tr>
     <tr align=right><td><u> ",(double)($val*$li),"</u> Litres</td></tr>
     <tr align=right><td><u> ",(double)($val*$ya),"</u> Yards<sup>3</sup></td></tr>
     <tr align=right><td><u> ",(double)($val*$qtk),"</u> Quart(UK)</td></tr></table>";

How do I optimize this in a way that I can save all the conversion values (I'm thinking possibly in an associative array) and still be able to display one conversion based on user selection in the "to" select instead of outputting all of the converted units as seen above?


1 Answer 1


Convert the from to a single unit, and convert that single unit to to. You don't have to compute conversions for every single pair.

  • \$\begingroup\$ Can you please clarify on how that can be done? Thanks \$\endgroup\$
    – Eddy Cozmo
    May 5, 2016 at 17:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.