Search code examples
phpstringoutputecho

php how to echo string in output and format numbers


Hi i am trying to echo and output where the height is correctly displayed as 5ft 8ins however i am unaware how to do this. I am new to programming so any help would be appreciated.

The end result should look like: Height in feet and inches: 5ft 8ins

$heightMeters = 1.75;
$heightInches = $heightMeters * 100 /2.54;
$heightFeet = $heightInches / 12;
echo 'Height in Feet and inches: '.$heightFeet;

Solution

  • Try the following (explanation in code comments):

    // given height in meters
    $heightMeters = 1.75;
    
    // convert the given height into inches
    $heightInches = $heightMeters * 100 /2.54;
    
    // feet = integer quotient of inches divided by 12
    $heightFeet = floor($heightInches / 12);
    
    // balance inches after $heightfeet
    // so if 68 inches, balance would be remainder of 68 divided by 12 = 4
    $balanceInches = floor($heightInches % 12);
    
    // prepare display string for the height
    $heightStr = 'Height in Feet and inches: ';
    // If feet is greater than zero then add it to string
    $heightStr .= ($heightFeet > 0 ? $heightFeet . 'ft ' : '');
    // If balance inches is greater than zero then add it to string
    $heightStr .= ($balanceInches > 0 ? $balanceInches . 'ins' : '');
    
    // Display the string
    echo $heightStr;