Page 1 of 1

maths from string?

Posted: Mon Nov 06, 2006 9:22 am
by php3ch0
Hi I have a problem

I am writing a voucher script for my website. I need to perform a maths equation on a string. e.g

$var1 = "/2"; (string)
$var2 = "20"; (int)

I need to perform the string function on the int to make $amount = (20 / 2); I could have various strings e.g $var could be "-10"; or "*3"

then store that as a variable.

Am i making sense?

Posted: Mon Nov 06, 2006 9:28 am
by JayBird
Perhaps use eval()?

Posted: Mon Nov 06, 2006 9:34 am
by php3ch0
i have tried

Code: Select all

$amount = "20";
maths ="/2";

$amount = eval($amount."".$maths);
and get a parse error. Am I on the right track?

Posted: Mon Nov 06, 2006 9:41 am
by JayBird

Code: Select all

$amount = "20";
$maths ="/2";

$equation = "\$answer=".$amount.$maths.";";

eval($equation);

echo $answer;

Posted: Mon Nov 06, 2006 9:48 am
by php3ch0
Works great thanks

Posted: Mon Nov 06, 2006 9:50 am
by timvw
I would strongly recommend against eval... I believe there's a Math_RPN package in pear...

Code: Select all

$rpn = new Math_Rpn();
echo $rpn->calculate($expression,'deg',false);