muqsit / arithmexp
Mathematical expression parser and evaluator for PHP
Requires
- php: ^8.1
Requires (Dev)
- phpunit/phpunit: ^9
This package is auto-updated.
Last update: 2024-05-31 00:23:22 UTC
README
arithmexp
is a powerful mathematical expression parser and evaluator library for PHP with support for variable substitution, constant declaration, deterministic and non-deterministic function registration, and more.
Test out the parser on the demo site!
Installation with composer
composer require muqsit/arithmexp
Evaluating a mathematical expression
To evaluate a mathematical expression, a Parser
instance must first be constructed.
The mathematical expression string must be passed in Parser::parse()
to obtain a reusable Expression
instance.
The value of the mathematical expression can then be evaluated by invoking Expression::evaluate()
.
$parser = Parser::createDefault(); $expression = $parser->parse("2 + 3"); var_dump($expression->evaluate()); // int(5)
To substitute values of variables that occur within the supplied expression, an array<string, int|float>
must be passed to Expression::evaluate()
.
$expression = $parser->parse("x + y"); var_dump($expression->evaluate(["x" => 2, "y" => 3])); // int(5) var_dump($expression->evaluate(["x" => 1.5, "y" => 1.5])); // float(3)
The return value type of the evaluation is consistent with that of PHP's. As such, int + int
returns an int
value, whereas a float + int|float
returns a float
value. See documentation notes in the wiki for more details.