tags:

views:

314

answers:

3

What i am really looking for is a maths equation function that takes in a string representing and equation and calculates the answer as a return type

For Example "(((4 * 5) + 6) * 2) / 8"

OutPut: 6.5

So in coding tearms something like

print calc("(((4 * 5) + 6) * 2) / 8");

Is there already a class or a function that some angel has built or do i gota do it my self

Thanks

+3  A: 

you can use eval() for that, it'll evaluate the argument as php code:

$result = eval("(((4 * 5) + 6) * 2) / 8"); // 6.5
print $result;
cloudhead
I literally copies and pasted to make sure but it saysParse error: syntax error, unexpected $end in xxxxxxxxxxxxxxx/test.php(12) : eval()'d code on line 1
Shahmir Javaid
Even eval("4+5") gives the same error
Shahmir Javaid
ah yea sorry about that, you should assign it to a variable, gonna edit the answer.
cloudhead
Try this one: eval("\$test = (((4 * 5) + 6) * 2) / 8;"); print $test; The backslash before $test is important!
merkuro
Just an additional note: Please be aware that user input not sanitized will lead to problems!
merkuro
need another edit on that, the one that worked waseval("\$test = (((4 * 5) + 6) * 2) / 8;");print $test;as merkuro suggested
Shahmir Javaid
+1  A: 

If you end up rolling your own, read Smart design of a math parser or Equation expression parser with precedence. With explicit parentheses as in your example the parser would be much simpler.

Jared Updike
+2  A: 

As cloudhead said, just fixed up.

$nums = "(((4 * 5) + 6) * 2) / 8";
eval("\$nums = $nums;");
echo $nums;
Ian Elliott