3

I have an array of fractions:

$fractions = array('1/8', '1/4', '1/2');

Is there any way that I can get PHP to actually perform the division to get a decimal value?

Something like:

foreach($fractions as $value) {
    $decimal = [the result of 1 divided by 8, or whatever the current fraction is in value];
}
2
  • 1
    You can construct your array much better, but if you won't - as AJ said, use eval() Commented May 18, 2011 at 22:14
  • The array was simply to help illustrate the question. Commented May 19, 2011 at 13:48

2 Answers 2

6

The way you have it, you should just explode and do your division:

foreach($fractions as $value) {
    $exp = explode('/',$value);
    $decimal =  $exp[0] /  $exp[1];
}

You could also eval(), but I usually try not to do that. It is a performance hit as well.

Sign up to request clarification or add additional context in comments.

Comments

3

You can call eval():

$fractions = array('1/8', '1/4', '1/2');

foreach($fractions as $value) {
    $decimal = eval("return $value;");
    echo "$value = $decimal\n";
}

2 Comments

For this to work the line must read $decimal = eval("return $value;"); or the eval will fail with Parse error: syntax error, unexpected $end. I don't really like using eval either
Thanks for the additional suggestion AJ. I will keep eval in mind for possible future use.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.