Execute and calculate string as a mathematical equation in PHP

Suppose we have a string of mathematical expression and we need to calculate and then get the value of the expression using PHP. How can we do it?

Now, we are going to learn how to execute a string as a mathematical expression and then calculate the value.

At first, we are going to see the example PHP code:

$string = "(11+10)*3";
$math_string ="print (".$string.");";
$result = eval($math_string);
echo $result;

If we run the above code, it will return the result we can see below:


In the above code, we have used the PHP eval() function. The PHP eval function can take evaluate any string as PHP code. We have sent the string as the parameter to the eval function where our math expression string takes as PHP code and executed. We have stored the value in the variable and then show it on our page.

Detect the browser in PHP

Detect The Country Of The Visitor In PHP

That’s it. We have just used few lines of code and able to execute and calculate string as a mathematical equation using PHP. But we should always keep in mind that the string should be a proper mathematical equation and it should be in proper format.

Also, remember that the eval function is always dangerous. We never should take input from the users without proper validation. It is always recommended not to use this function if there is any other way available. If this function needed to be used, then always validate it properly.

Leave a Reply

Your email address will not be published. Required fields are marked *