ryangjchandler / mathexpr
A tiny math expression evaluator written in PHP.
Fund package maintenance!
ryangjchandler
Requires
- php: ^8.1
- ryangjchandler/lexical: ^0.1.1
Requires (Dev)
- laravel/pint: ^1.2
- pestphp/pest: ^1.20
- spatie/ray: ^1.28
- symfony/var-dumper: ^6.3
This package is auto-updated.
Last update: 2024-10-09 17:54:28 UTC
README
This package provides a small evaluator for mathemetical expressions in PHP.
Installation
You can install the package via Composer:
composer require ryangjchandler/mathexpr
Usage
use RyanChandler\Mathexpr\Evaluator; $evaluator = new Evaluator(); $result = $evaluator->eval('1 + 2'); // -> (int) 3
Operators
Mathexpr supports the following operators:
+
-
*
/
%
Functions
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
Variables
Mathexpr has support for variables too.
$evaluator->addVariable('a', 1); $evaluator->addVariable('b', 2); $evaluator->eval('a + b'); // -> (int) 3
Constants
A small set of common mathematical constants are also available by default:
pi
/PI
tau
/TAU
e
/E
Testing
composer test
Changelog
Please see CHANGELOG for more information on what has changed recently.
Contributing
Please see CONTRIBUTING for details.
Security Vulnerabilities
Please review our security policy on how to report security vulnerabilities.
Credits
License
The MIT License (MIT). Please see License File for more information.