maths from string?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
php3ch0
Forum Contributor
Posts: 212
Joined: Sun Nov 13, 2005 7:35 am
Location: Folkestone, Kent, UK

maths from string?

Post 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?
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Perhaps use eval()?
User avatar
php3ch0
Forum Contributor
Posts: 212
Joined: Sun Nov 13, 2005 7:35 am
Location: Folkestone, Kent, UK

Post 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?
User avatar
JayBird
Admin
Posts: 4524
Joined: Wed Aug 13, 2003 7:02 am
Location: York, UK
Contact:

Post by JayBird »

Code: Select all

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

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

eval($equation);

echo $answer;
User avatar
php3ch0
Forum Contributor
Posts: 212
Joined: Sun Nov 13, 2005 7:35 am
Location: Folkestone, Kent, UK

Post by php3ch0 »

Works great thanks
timvw
DevNet Master
Posts: 4897
Joined: Mon Jan 19, 2004 11:11 pm
Location: Leuven, Belgium

Post 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);
Post Reply