How do I calculate a math expression in the form of a string to an output using PHP?
<?php
$ma ="min(2+10,5*1,max(8/2,8-2,abs(-10)))"; // math expression
print $ma; // output of the calculation
?>
How do I calculate a math expression in the form of a string to an output using PHP?
<?php
$ma ="min(2+10,5*1,max(8/2,8-2,abs(-10)))"; // math expression
print $ma; // output of the calculation
?>
I made a math_eval
helper function package that should do exactly want you need.
Example usage:
require 'vendor/autoload.php';
$two = math_eval('1 + 1');
$three = math_eval('5 - 2');
$ten = math_eval('2 * 5');
$four = math_eval('8 / 2');
Link: https://github.com/langleyfoxall/math_eval
In the background, this wraps around the mossadal/math-parser package.
I've found some parsers on GitHub, this one looks very interesting:
mossadal/math-parser: PHP parser for mathematical expressions
It can be used this way:
use MathParser\StdMathParser;
use MathParser\Interpreting\Evaluator;
$parser = new StdMathParser();
// Generate an abstract syntax tree
$AST = $parser->parse('1+2');
// Do something with the AST, e.g. evaluate the expression:
$evaluator = new Evaluator();
$value = $AST->accept($evaluator);
echo $value;
It can also be used with functions like cos()
or sin()
.