views:

337

answers:

3

I'm creating table for defining an individual's BMI. The chart (as yet) doesn't take input (because I want to make the thing work stand-alone, first), but it does show (on parallel axes) the height in both metres and feet/inches.

In order to do this I'm defining the metres' start point and range and then converting the defined metres variables into feet/inches, to do which I've come up with (please don't laugh...) the following:

<?php
     $m; // height in m

     $hInInches = ($m*3.2808399)*12;

     $hInImp = explode(".",$hInInches);

     $hInFt = $hInImp[0];

     $hInInches = substr(12*$hInImp[1],0,2);
?>

I was wondering if anyone has any prettier, more economical, more accurate means by which this could be done, since this is being run inside of a for () loop to generate x numbers of rows (defined elswhere), and I'd like (if possible) to reduce the load...

Thanks for any help!

A: 

i'm not sure if you consider this prettier; however, I'd argue that an ajax/javascript solution might be idea. As the user enters the value, the results update.

with regards to your code
* define M_TO_FEET, FEET_TO_INCH constants.
* define 2 equations feet_to_metres(value_to_convert) and metres_to_feet(value_to_convert)
* write the conversion code in each and let it return the result

and then you can create a simple if statement:
* If user inputs metres, then metres_to_feet(value_entered_by_user)
dassouki
+2  A: 

Here is an approach, in psuedo-code:

inches_per_meter = 39.3700787
inches_total = round(meters * inches_per_meter)  /* round to integer */
feet = inches_total / 12  /* assumes division truncates result; if not use floor() */
inches = inches_total % 12 /* modulus */

You could pull out the 12 to a constant as well...

derobert
Thanks derobert, the concept of using a constant hadn't occurred 'til I read these answers...can you tell I'm noob at php? O.o thanks again! =)
David Thomas
+1  A: 

To me you should avoid the string manipulation functions as derobert already stated. In php the code should be similar to the following one:

<?php
   $m=2; // height in m
    $hInFeet= $m*3.2808399;
$hFeet=(int)$hInFeet; // truncate the float to an integer
    $hInches=round(($hInFeet-$hFeet)*12); 
?>

Just two multiply and a subtraction (plus a function call to round) are quite economic, and the code is quite readable too.

Eineki