This package provides a small evaluator for mathemetical expressions in PHP.
You can install the package via Composer:
composer require ryangjchandler/mathexpr
use RyanChandler\Mathexpr\Evaluator;
$evaluator = new Evaluator();
$result = $evaluator->eval('1 + 2'); // -> (int) 3
Mathexpr supports the following operators:
+
-
*
/
%
Out of the box, Mathexpr provides a set of useful mathematical functions that can be called in an expression.
$evaluator->eval('sum(1, 2, 3)')
You can also extend the default set with your own custom functions.
$evaluator->addFunction('clamp', function (int|float $subject, int|float $min, int|float $max): int|float {
return max($min, min($max, $subject));
});
$evaluator->eval('clamp(200, 10, 100)'); // -> (int) 100
Mathexpr has support for variables too.
$evaluator->addVariable('a', 1);
$evaluator->addVariable('b', 2);
$evaluator->eval('a + b'); // -> (int) 3
A small set of common mathematical constants are also available by default:
pi
/PI
tau
/TAU
e
/E
composer test
Please see CHANGELOG for more information on what has changed recently.
Please see CONTRIBUTING for details.
Please review our security policy on how to report security vulnerabilities.
The MIT License (MIT). Please see License File for more information.