Gordonmac Dot Com

Mostly a web development blog

Prettier PHP meter to feet/inches conversions

Posted: February 15th, 2011 | Tags: | Posted in: PHP, Tutorials
Note: This tutorial was originally published in 2011. The tips and techniques explained may be outdated.

Whilst it’s fairly simple to convert meters to feet and inches using PHP the resulting conversion often looks rather complex and untidy.

For example, most conversions will end up looking something like this: 12 meters = 39.3700 feet. This is not very pretty and looks overly complicated when you consider that most people express feet and inches like this: 39′ 4″.

The following PHP function will convert meters to feet in a user friendly manner, easily recognised by most people.

The PHP Code

<?php
function metersToFeetInches($meters, $echo = true)
{
	$m = $meters;
	$valInFeet = $m*3.2808399;
	$valFeet = (int)$valInFeet;
	$valInches = round(($valInFeet-$valFeet)*12);
	$data = $valFeet."&prime;".$valInches."&Prime;";
	if($echo == true)
	{
		echo $data;
	} else {
		return $data;
	}
}
?>

Usage

To echo out the converted data simply call the function like this:

<?php metersToFeetInches(12); ?>

To assign the converted data to a variable call the function like this:

<?php
$feetInches = metersToFeetInches(12,false);
echo $feetInches;
?>

Have fun :)