PHP: Convert cm or meters into feet and inches.

In this tutorial, we are going to show you how to convert centimetres and meters into feet and inches using PHP.

As you probably already know, a lot of people are better at visualizing feet and inches in their heads. As a result, displaying meters or centimetres might not work.

How to convert centimetres into feet and inches.

Take a look at the following function.

/**
 * Convert centimetres into feet and inches.
 * 
 * @param float $cm
 * @return string
 */
function cm2feet($cm){
    //Convert the cm into inches by multiplying the figure by 0.393701
    $inches = round($cm * 0.393701);
    //Get the feet by dividing the inches by 12.
    $feet = intval($inches / 12);
    //Then, get the remainder of that division.
    $inches = $inches % 12;
    //If there is no remainder, then it's an even figure
    if($inches == 0){
        return $feet . ' foot';
    }
    //Otherwise, return it in ft and inches.
    return sprintf('%d ft %d inches', $feet, $inches);
}

In the code above, we did the following.

  1. We convert our centimetres into inches by multiplying the number by 0.393701. We also use PHP’s round function in order to round this figure to the closest whole number.
  2. After that, we get the feet by dividing the inches by 12. This is because there are 12 inches in a foot.
  3. Finally, we get the remainder of that division sum by using PHP’s modulo operator.

If there is no remainder, then it means that there are no inches. In other words, the result is “5 foot” or “6 foot”, etc.

However, if there is a remainder, then our function will return the full string in ft and inches. For example, “5ft 10 inches”.

How to convert meters into feet and inches using PHP.

To convert meters into feet and inches, all we need to do is multiply the meter number by 100 and then do the exact same thing as we did above.

Because we know that there are 100 centimetres in a meter, we can easily convert meters into feet and inches by doing the following.

/**
 * Convert meters into feet and inches.
 * 
 * @param float $meters
 * @return string
 */
function meters2feet($meters){
    //Convert the meters into cm
    $cm = $meters * 100;
    //Convert the cm into inches by multiplying the figure by 0.393701
    $inches = round($cm * 0.393701);
    //Get the feet by dividing the inches by 12.
    $feet = intval($inches/12);
    //Then, get the remainder of that division.
    $inches = $inches % 12;
    //If there is no remainder, then it's an even figure
    if($inches == 0){
        return $feet . ' foot';
    }
    //Otherwise, return it in ft and inches.
    return sprintf('%d ft %d inches', $feet, $inches);
}

As you can see, this function is almost identical to the previous one. However, in this case, we convert our meters into centimeters before we work out the feet and inches.