2

Is it possible to calculate a math function f(x) that in a string. Something like this:

$function = '2x+3';
$x = 4;
math_function($function, $x); //Shoud produce 11

I can't find a library for tasks like this on PHP.net or with Google, but I don't think I am the first one that wants this?

1 Answer 1

3

My standard answer to this question whenever it crops up:

Don't use eval (especially if the formula contains user input) or reinvent the wheel by writing your own formula parser.

Take a look at the evalMath class on PHPClasses. It should do everything that you want in a nice safe sandbox.

Sign up to request clarification or add additional context in comments.

6 Comments

+1... Building a math formula parser is a great academic problem (since there are many well defined edge-cases which yield to a non-trivial solution). But in terms of a practical problem, it's not worth the effort since there are tools built for it...
Wow, that was quick! Thank you very much. I didn't even know the existence of eval()! I will take a look at it.
I'm confused: You say "Don't use eval" and then advice the use of a class that does exactly that. (Still perfectly valid answer that solves ops problem. So +1, even if the evalMath code makes me want to vomit ;) )
@edorian - evalMath does NOT use eval! It uses Djikstra's shunting yard to parse the formula onto a stack, then processes operations using standard PHP methods in a controlled sandbox
@edorian - that instance could also be replaced with $r = call_user_func($fnn,$op1);$stack->push($r); which is cleaner than using eval(), and that's not dissimilar to what I did with my own math parser.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.