PHP: Calculate a math function f(x) in a string

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 or with Google, but I don’t think I am the first one that wants this?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply