PHPackages                             nxp/math-executor - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Parsing &amp; Serialization](/categories/parsing)
4. /
5. nxp/math-executor

ActiveLibrary[Parsing &amp; Serialization](/categories/parsing)

nxp/math-executor
=================

Simple math expressions calculator

v2.3.8(6mo ago)2281.7M—9.1%496MITPHPPHP &gt;=8.0 &lt;8.6CI passing

Since Sep 6Pushed 6mo ago13 watchersCompare

[ Source](https://github.com/NeonXP/MathExecutor)[ Packagist](https://packagist.org/packages/nxp/math-executor)[ Docs](http://github.com/NeonXP/MathExecutor)[ RSS](/packages/nxp-math-executor/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (10)Dependencies (3)Versions (45)Used By (6)

MathExecutor [![Tests](https://github.com/neonxp/MathExecutor/workflows/Tests/badge.svg)](https://github.com/neonxp/MathExecutor/actions?query=workflow%3ATests) [![](https://camo.githubusercontent.com/742e8be8005b1fe76a64a5d8f5e6a5d4f63bf315e9a44a6d23e4e11c76b0555f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230362d627269676874677265656e2e7376673f7374796c653d666c6174)](https://camo.githubusercontent.com/742e8be8005b1fe76a64a5d8f5e6a5d4f63bf315e9a44a6d23e4e11c76b0555f/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048505374616e2d6c6576656c253230362d627269676874677265656e2e7376673f7374796c653d666c6174)
======================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================================

[](#mathexecutor--)

A simple and extensible math expressions calculator
===================================================

[](#a-simple-and-extensible-math-expressions-calculator)

Features:
---------

[](#features)

- Built in support for +, -, \*, /, % and power (^) operators
- Parentheses () and arrays \[\] are fully supported
- Logical operators (==, !=, &lt;, &lt;, &gt;=, &lt;=, &amp;&amp;, ||, !)
- Built in support for most PHP math functions
- Support for BCMath Arbitrary Precision Math
- Support for variable number of function parameters and optional function parameters
- Conditional If logic
- Support for user defined operators
- Support for user defined functions
- Support for math on user defined objects
- Dynamic variable resolution (delayed computation)
- Unlimited variable name lengths
- String support, as function parameters or as evaluated as a number by PHP
- Exceptions on divide by zero, or treat as zero
- Unary Plus and Minus (e.g. +3 or -sin(12))
- Pi ($pi) and Euler's number ($e) support to 11 decimal places
- Easily extensible

Install via Composer:
---------------------

[](#install-via-composer)

```
composer require nxp/math-executor

```

Sample usage:
-------------

[](#sample-usage)

```
use NXP\MathExecutor;

$executor = new MathExecutor();

echo $executor->execute('1 + 2 * (2 - (4+10))^2 + sin(10)');
```

Functions:
----------

[](#functions)

Default functions:

- abs
- acos (arccos)
- acosh
- arccos
- arccosec
- arccot
- arccotan
- arccsc (arccosec)
- arcctg (arccot, arccotan)
- arcsec
- arcsin
- arctan
- arctg
- array
- asin (arcsin)
- atan (atn, arctan, arctg)
- atan2
- atanh
- atn
- avg
- bindec
- ceil
- cos
- cosec
- cosec (csc)
- cosh
- cot
- cotan
- cotg
- csc
- ctg (cot, cotan, cotg, ctn)
- ctn
- decbin
- dechex
- decoct
- deg2rad
- exp
- expm1
- floor
- fmod
- hexdec
- hypot
- if
- intdiv
- lg
- ln
- log (ln)
- log10 (lg)
- log1p
- max
- median
- min
- octdec
- pi
- pow
- rad2deg
- round
- sec
- sin
- sinh
- sqrt
- tan (tn, tg)
- tanh
- tg
- tn

Add custom function to executor:

```
$executor->addFunction('concat', function($arg1, $arg2) {return $arg1 . $arg2;});
```

Optional parameters:

```
$executor->addFunction('round', function($num, int $precision = 0) {return round($num, $precision);});
$executor->execute('round(17.119)'); // 17
$executor->execute('round(17.119, 2)'); // 17.12
```

Variable number of parameters:

```
$executor->addFunction('average', function(...$args) {return array_sum($args) / count($args);});
$executor->execute('average(1,3)'); // 2
$executor->execute('average(1, 3, 4, 8)'); // 4
```

Operators:
----------

[](#operators)

Default operators: `+ - * / % ^`

Add custom float modulo operator to executor:

```
use NXP\Classes\Operator;

$executor->addOperator(new Operator(
    '%', // Operator sign
    false, // Is right associated operator
    180, // Operator priority
    function ($op1, $op2)
    {
       return fmod($op1, $op2);
    }
));
```

Logical operators:
------------------

[](#logical-operators)

Logical operators (==, !=, &lt;, &lt;, &gt;=, &lt;=, &amp;&amp;, ||, !) are supported, but logically they can only return true (1) or false (0). In order to leverage them, use the built in **if** function:

```
if($a > $b, $a - $b, $b - $a)

```

You can think of the **if** function as prototyped like:

```
function if($condition, $returnIfTrue, $returnIfFalse)

```

Variables:
----------

[](#variables)

Variables can be prefixed with the dollar sign ($) for PHP compatibility, but is not required.

Default variables:

```
$pi = 3.14159265359
$e  = 2.71828182846

```

You can add your own variables to executor:

```
$executor->setVar('var1', 0.15)->setVar('var2', 0.22);

echo $executor->execute("$var1 + var2");
```

Arrays are also supported (as variables, as func params or can be returned in user defined funcs):

```
$executor->setVar('monthly_salaries', [1800, 1900, 1200, 1600]);

echo $executor->execute("avg(monthly_salaries) * min([1.1, 1.3])");
```

By default, variables must be scalar values (int, float, bool or string) or array. If you would like to support another type, use **setVarValidationHandler**

```
$executor->setVarValidationHandler(function (string $name, $variable) {
    // allow all scalars, array and null
    if (is_scalar($variable) || is_array($variable) || $variable === null) {
        return;
    }
    // Allow variables of type DateTime, but not others
    if (! $variable instanceof \DateTime) {
        throw new MathExecutorException("Invalid variable type");
    }
});
```

You can dynamically define variables at run time. If a variable has a high computation cost, but might not be used, then you can define an undefined variable handler. It will only get called when the variable is used, rather than having to always set it initially.

```
$executor->setVarNotFoundHandler(
    function ($varName) {
        if ($varName == 'trans') {
            return transmogrify();
        }
        return null;
    }
);
```

Floating Point BCMath Support
-----------------------------

[](#floating-point-bcmath-support)

By default, `MathExecutor` uses PHP floating point math, but if you need a fixed precision, call **useBCMath()**. Precision defaults to 2 decimal points, or pass the required number. `WARNING`: Functions may return a PHP floating point number. By doing the basic math functions on the results, you will get back a fixed number of decimal points. Use a plus sign in front of any stand alone function to return the proper number of decimal places.

Division By Zero Support:
-------------------------

[](#division-by-zero-support)

Division by zero throws a `\NXP\Exception\DivisionByZeroException` by default

```
try {
    echo $executor->execute('1/0');
} catch (DivisionByZeroException $e) {
    echo $e->getMessage();
}
```

Or call setDivisionByZeroIsZero

```
echo $executor->setDivisionByZeroIsZero()->execute('1/0');
```

If you want another behavior, you can override division operator:

```
$executor->addOperator(new Operator("/", false, 180, function($a, $b) {
    if ($b == 0) {
        return null;
    }
    return $a / $b;
});
echo $executor->execute('1/0');
```

String Support:
---------------

[](#string-support)

Expressions can contain double or single quoted strings that are evaluated the same way as PHP evaluates strings as numbers. You can also pass strings to functions.

```
echo $executor->execute("1 + '2.5' * '.5' + myFunction('category')");
```

To use reverse solidus character (\\) in strings, or to use single quote character (') in a single quoted string, or to use double quote character (") in a double quoted string, you must prepend reverse solidus character (\\).

```
echo $executor->execute("countArticleSentences('My Best Article\'s Title')");
```

Extending MathExecutor
----------------------

[](#extending-mathexecutor)

You can add operators, functions and variables with the public methods in MathExecutor, but if you need to do more serious modifications to base behaviors, the easiest way to extend MathExecutor is to redefine the following methods in your derived class:

- defaultOperators
- defaultFunctions
- defaultVars

This will allow you to remove functions and operators if needed, or implement different types more simply.

Also note that you can replace an existing default operator by adding a new operator with the same regular expression string. For example if you just need to redefine TokenPlus, you can just add a new operator with the same regex string, in this case '\\+'.

Documentation
-------------

[](#documentation)

Full class documentation via [PHPFUI/InstaDoc](http://phpfui.com/?n=NXP&c=MathExecutor)

Future Enhancements
-------------------

[](#future-enhancements)

This package will continue to track currently supported versions of PHP.

###  Health Score

68

—

FairBetter than 100% of packages

Maintenance67

Regular maintenance activity

Popularity60

Solid adoption and visibility

Community35

Small or concentrated contributor base

Maturity93

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 68.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~103 days

Recently: every ~240 days

Total

44

Last Release

192d ago

Major Versions

v0.8.0 → V1.0.02019-10-31

V1.1.4 → v2.0.02020-05-20

PHP version history (10 changes)v0.3PHP &gt;=5.6

V1.0.0PHP &gt;=7.1

V2.1.6PHP &gt;=7.2

V2.1.10PHP &gt;=7.3

v2.2.0PHP &gt;=7.4

v2.3.3PHP &gt;=8.0

v2.3.4PHP &gt;=8.0 &lt;8.3

v2.3.5PHP &gt;=8.0 &lt;8.4

v2.3.7PHP &gt;=8.0 &lt;8.5

v2.3.8PHP &gt;=8.0 &lt;8.6

### Community

Maintainers

![](https://www.gravatar.com/avatar/7bff91e9bc8601ba57f9d79fb3d5db7c09fe3b03cbec0f33acc6a9a1ecfb1492?d=identicon)[NeonXP](/maintainers/NeonXP)

---

Top Contributors

[![phpfui](https://avatars.githubusercontent.com/u/7434059?v=4)](https://github.com/phpfui "phpfui (95 commits)")[![javiermarinros](https://avatars.githubusercontent.com/u/840412?v=4)](https://github.com/javiermarinros "javiermarinros (10 commits)")[![neonxp](https://avatars.githubusercontent.com/u/190940?v=4)](https://github.com/neonxp "neonxp (9 commits)")[![fatihkizmaz](https://avatars.githubusercontent.com/u/17065192?v=4)](https://github.com/fatihkizmaz "fatihkizmaz (5 commits)")[![msztorc](https://avatars.githubusercontent.com/u/7062526?v=4)](https://github.com/msztorc "msztorc (3 commits)")[![ochi51](https://avatars.githubusercontent.com/u/5582393?v=4)](https://github.com/ochi51 "ochi51 (2 commits)")[![johnrazeur](https://avatars.githubusercontent.com/u/1339931?v=4)](https://github.com/johnrazeur "johnrazeur (2 commits)")[![bajb](https://avatars.githubusercontent.com/u/2241334?v=4)](https://github.com/bajb "bajb (2 commits)")[![waffle-iron](https://avatars.githubusercontent.com/u/6912981?v=4)](https://github.com/waffle-iron "waffle-iron (1 commits)")[![AntonStoeckl](https://avatars.githubusercontent.com/u/776322?v=4)](https://github.com/AntonStoeckl "AntonStoeckl (1 commits)")[![ZhukV](https://avatars.githubusercontent.com/u/2256109?v=4)](https://github.com/ZhukV "ZhukV (1 commits)")[![beblife](https://avatars.githubusercontent.com/u/9271492?v=4)](https://github.com/beblife "beblife (1 commits)")[![diman3210](https://avatars.githubusercontent.com/u/25133537?v=4)](https://github.com/diman3210 "diman3210 (1 commits)")[![madman-81](https://avatars.githubusercontent.com/u/50033071?v=4)](https://github.com/madman-81 "madman-81 (1 commits)")[![mathijsqdrop](https://avatars.githubusercontent.com/u/101415133?v=4)](https://github.com/mathijsqdrop "mathijsqdrop (1 commits)")[![mrm](https://avatars.githubusercontent.com/u/141798?v=4)](https://github.com/mrm "mrm (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")[![shadoWalker89](https://avatars.githubusercontent.com/u/1449151?v=4)](https://github.com/shadoWalker89 "shadoWalker89 (1 commits)")

---

Tags

expressionexpression-evaluatormathmathematicsphpparsermathexpressioncalculatorformulamathmatics

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/nxp-math-executor/health.svg)

```
[![Health](https://phpackages.com/badges/nxp-math-executor/health.svg)](https://phpackages.com/packages/nxp-math-executor)
```

###  Alternatives

[nikic/php-parser

A PHP parser written in PHP

17.4k902.6M1.8k](/packages/nikic-php-parser)[madorin/matex

PHP Mathematical expression parser and evaluator

1161.2M1](/packages/madorin-matex)[doctrine/lexer

PHP Doctrine Lexer parser library that can be used in Top-Down, Recursive Descent Parsers.

11.2k910.8M118](/packages/doctrine-lexer)[masterminds/html5

An HTML5 parser and serializer.

1.8k242.8M229](/packages/masterminds-html5)[denissimon/formula-parser

Parsing and evaluating mathematical formulas given as strings.

81306.8k3](/packages/denissimon-formula-parser)[chriskonnertz/string-calc

StringCalc is a PHP calculator library for mathematical terms (expressions) passed as strings.

102643.3k5](/packages/chriskonnertz-string-calc)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
