0

I wanted the math operation to be done directly from the form post value. Is there a function to accomplish this? I tried this, but it just echo's out the input value as it is:

<form action="" method="post">
<input type="text" name="equation" value="2+(3+4)">
<input type="submit" value="Calculate">
</form>

 <?php
 if(isset($_POST['equation'])){
   $equation = htmlspecialchars($_POST['equation']);
 echo $equation;
}
?>

As you see, i like to get the output of 2+(3+4) while echo the $equation.

user2672112
  • 199
  • 1
  • 14
  • Why would you do it that way? – Paul Dessert Dec 24 '14 at 07:22
  • You have to build your own function. If you want to do direct math, build it in your PHP or get user input then assign it to variables and do the math from there. – Funk Forty Niner Dec 24 '14 at 07:22
  • possible duplicate of [calculate math expression from a string using eval](http://stackoverflow.com/questions/18880772/calculate-math-expression-from-a-string-using-eval) – nitigyan Dec 24 '14 at 07:25
  • possible duplicate of [php calculate formula in string](http://stackoverflow.com/questions/14999578/php-calculate-formula-in-string) – Mangesh Parte Dec 24 '14 at 07:28

2 Answers2

1

try this

$equation = preg_replace('[^0-9\+-\*\/\(\) ]', '', $_POST['equation']);
if(!empty($equation)){
   eval( '$total = (' . $equation . ');' );
   echo $total;
}

You have to take care about the security or use preg_replace and/or put some conditions.

Ram Sharma
  • 8,676
  • 7
  • 43
  • 56
  • 1
    Ram you're awesome bro. Thanks :) I'll take care of the security . But thanks a lot for the method.. amazing.. – user2672112 Dec 24 '14 at 07:29
1

Usually people use eval for this purpose, but it's better not to use eval, it is not a good pratice, it's a big hole in security.

function calc($str)
{
    $str = preg_replace('[^0-9\+-\*\/\(\) ]', '', $str); 

    $compute = create_function('', 'return (' . $str . ');' );
    return 0 + $compute();
}

echo calc($_POST['equation']);
Alex Pliutau
  • 21,392
  • 27
  • 113
  • 143