Help with caclulating using eval

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
mushpoc
Forum Newbie
Posts: 6
Joined: Wed Jan 14, 2009 11:25 pm

Help with caclulating using eval

Post 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.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Re: Help with caclulating using eval

Post 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?
mushpoc
Forum Newbie
Posts: 6
Joined: Wed Jan 14, 2009 11:25 pm

Re: Help with caclulating using eval

Post 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],");
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Re: Help with caclulating using eval

Post 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['-'];
 
mushpoc
Forum Newbie
Posts: 6
Joined: Wed Jan 14, 2009 11:25 pm

Re: Help with caclulating using eval

Post by mushpoc »

ohhh ok, another question how would i do a is_numeric check
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Re: Help with caclulating using eval

Post by Burrito »

Code: Select all

 
if(is_numeric($firstNum))
  // do stuff
else
  // don't do stuff
 
mushpoc
Forum Newbie
Posts: 6
Joined: Wed Jan 14, 2009 11:25 pm

Re: Help with caclulating using eval

Post 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?
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: Help with caclulating using eval

Post 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.
Last edited by requinix on Tue Jan 20, 2009 5:33 pm, edited 1 time in total.
User avatar
Burrito
Spockulator
Posts: 4715
Joined: Wed Feb 04, 2004 8:15 pm
Location: Eden, Utah

Re: Help with caclulating using eval

Post by Burrito »

you could test it first and throw an exception if it's trying to divide by 0.
Post Reply