Page 1 of 1

Help with caclulating using eval

Posted: Tue Jan 20, 2009 3:36 pm
by mushpoc
$math['+']= $firstNum+$secondNumb;
$math['-']= $firstNum-$secondNumb;

eval ("print $math");

This is what i have, it is all comming from a form on what the user selects, but when they submit it it blows up.

Re: Help with caclulating using eval

Posted: Tue Jan 20, 2009 3:41 pm
by Burrito
eval() is used to evaluate a string as PHP code.

you have $math set up as an array, so evaluating "print $math" isn't going to do anything for you as you're basically trying to echo an array.

what exactly are you trying to do here?

Re: Help with caclulating using eval

Posted: Tue Jan 20, 2009 3:49 pm
by mushpoc
Im trying to calculate the user input of firstnumber + secondnumber

would this be more closer to what i am trying to get at:

eval ("print $math [$op],");

Re: Help with caclulating using eval

Posted: Tue Jan 20, 2009 3:53 pm
by Burrito
frankly I don't see a reason to use eval() here.

Code: Select all

 
$firstNum = 5;
$secondNum = 3;
$math['+']= $firstNum+$secondNum;
$math['-']= $firstNum-$secondNum;
echo $math['+'];
echo "<br>";
echo $math['-'];
 

Re: Help with caclulating using eval

Posted: Tue Jan 20, 2009 4:29 pm
by mushpoc
ohhh ok, another question how would i do a is_numeric check

Re: Help with caclulating using eval

Posted: Tue Jan 20, 2009 4:35 pm
by Burrito

Code: Select all

 
if(is_numeric($firstNum))
  // do stuff
else
  // don't do stuff
 

Re: Help with caclulating using eval

Posted: Tue Jan 20, 2009 4:51 pm
by mushpoc
ok i managed to get everything to work but when i try to divide by zero i get this "Warning: Division by zero"

is there a way to fix it?

Re: Help with caclulating using eval

Posted: Tue Jan 20, 2009 4:53 pm
by requinix
Don't divide by zero?

That was such an obvious answer I just had to say it.
If you have $a / $b and $b can't be zero then your code should check that $b!=0 before doing anything.

Re: Help with caclulating using eval

Posted: Tue Jan 20, 2009 4:57 pm
by Burrito
you could test it first and throw an exception if it's trying to divide by 0.