ryangjchandler/mathexpr

A tiny math expression evaluator written in PHP.

v0.1.0 2023-06-14 12:15 UTC

README

Latest Version on Packagist Tests Total Downloads

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.