Convert or parse a string containing feet and Inches to number in PHP

795

In my database, there is a field called height that is a varchar(9) field. The end user selects a value from a pull-down list that contains values such as:

5' 0
5' 0 1/2
5' 1
5' 1 1/2
5' 2
5' 2 1/2
And so on up to...
7' 4

What I need to do is convert this string into numeric inches for the purpose of a server-side calculation. I don't know how to approach this string conversion, so any assistance will be very much appreciated. Thank you!

227

Answer

Solution:

you want to get separate variables for feet, inches and fraction first

$toBeConverted = "5' 4 1/2";
list($feet,$inches,$frac) = explode(' ',$toBeConverted . ' ');

then add those values

$total = ((str_replace("'",'',$feet) * 12) + $inches + ($frac == '1/2' ? (1/2) : 0));
919

Answer

Solution:

$inches=0;
$array=explode(" ",$string);//where $string is "5' 0 1/2" for example
if ($array[2]='1/2') $inches=(int)$array[0]*12+(int)$array[1]+0.5;
    else $inches=(int)$array[0]*12+(int)$array[1];
967

Answer

Solution:

If you know the index of the pulldown, with the first value being 0, then the number of inches is

$inches = 60 + $pulldownIndex * 0.5;

Since you start at5' (5 * 12 = 60) and go up in increments of 0.5 inch.

Alternately, if you want to look at the string that was on the pulldown, I suggest you look at Felix's answer - it is very compact and elegant.

People are also looking for solutions to the problem: php - removing characters from string if it's not in the regex

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.