PHP Math Expression Evaluator: Parse and evaluate strings with math expressions

Recommend this page to a friend!

  Author Author  
Picture of Alexander Kiryukhin
Name: Alexander Kiryukhin <contact>
Classes: 2 packages by
Country: Russian Federation Russian Federation
Age: ???
All time rank: 241971 in Russian Federation Russian Federation
Week rank: 129 Up7 in Russian Federation Russian Federation Up


  Detailed description   Download Download .zip .tar.gz   Install with Composer Install with Composer  
This class can parse and evaluate strings with math expressions.

It can take a string with a math expression and evaluates it by computing the result of operations.

The class can be extended to handle new operations by specifying the operator symbol, priority of the operation and a callback function that will be used to evaluate the result of the operation.

Details
{startverticalbanner}
# MathExecutor [![Build Status](https://travis-ci.org/NeonXP/MathExecutor.png?branch=master)](https://travis-ci.org/NeonXP/MathExecutor) [![Latest Packagist release](https://img.shields.io/packagist/v/nxp/math-executor.svg)](https://packagist.org/packages/nxp/math-executor)

# A simple and extensible math expressions calculator

## Features:
* Built in support for +, -, *, / and power (^) operators plus ()
* Logical operators (==, !=, <, <, >=, <=, &&, ||)
* Built in support for most PHP math functions
* Conditional If logic
* Support for user defined operators
* Support for user defined functions
* 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 Minus (e.g. -3)
* Pi ($pi) and Euler's number ($e) support to 11 decimal places
* Easily extensible

## Install via Composer:
```
composer require nxp/math-executor
```

## Sample usage:
```php
use NXP\MathExecutor;

$executor = new MathExecutor();

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

## Functions:
Default functions:
* abs
* acos
* acosh
* asin
* atan (atn)
* atan2
* atanh
* avg
* bindec
* ceil
* cos
* cosh
* decbin
* dechex
* decoct
* deg2rad
* exp
* expm1
* floor
* fmod
* hexdec
* hypot
* if
* intdiv
* log
* log10
* log1p
* max
* min
* octdec
* pi
* pow
* rad2deg
* round
* sin
* sinh
* sqrt
* tan (tn)
* tanh

Add custom function to executor:
```php
$executor->addFunction('abs', function($arg) {return abs($arg);});
```
Function default parameters are not supported at this time.

## Operators:
Default operators: `+ - * / ^`

Add custom operator to executor:

```php
use NXP\Classes\Operator;

$executor->addOperator(new Operator(
    '%', // Operator sign
    false, // Is right associated operator
    170, // Operator priority
    function (&$stack)
    {
       $op2 = array_pop($stack);
       $op1 = array_pop($stack);
       $result = $op1->getValue() % $op2->getValue();

       return $result;
    }
));
```

## Logical operators:
Logical operators (==, !=, <, <, >=, <=, &&, ||) 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:
Default variables:

```
$pi = 3.14159265359
$e  = 2.71828182846
```

You can add your own variables to executor:

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

echo $executor->execute("$var1 + $var2");
```
## Division By Zero Support:
Division by zero throws a `\NXP\Exception\DivisionByZeroException` by default
```php
try {
    echo $executor->execute('1/0');
} catch (DivisionByZeroException $e) {
    echo $e->getMessage();
}
```
Or call setDivisionByZeroIsZero
```php
echo $executor->setDivisionByZeroIsZero()->execute('1/0');
```
If you want another behavior, you can override division operator:
```php
$executor->addOperator("/", false, 180, function($a, $b) {
    if ($b == 0) {
        return null;
    }
    return $a / $b;
});
echo $executor->execute('1/0');
```

## Unary Minus Operator:
Negative numbers are supported via the unary minus operator. Positive numbers are not explicitly supported as unsigned numbers are assumed positive.

## String Support:
Expressions can contain double or single quoted strings that are evaluated the same way as PHP evalutes strings as numbers. You can also pass strings to functions.

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

## 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 behaviours, 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

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

## Future Enhancements

This package will continue to track currently supported versions of PHP.  PHP 7.1 and earlier support will be dropped when PHP 8 is released.

  Classes of Alexander Kiryukhin  >  PHP Math Expression Evaluator  >  Download Download .zip .tar.gz  >  Support forum Support forum  >  Blog Blog  >  RSS 1.0 feed RSS 2.0 feed Latest changes  
Name: PHP Math Expression Evaluator
Base name: math-executor
Description: Parse and evaluate strings with math expressions
Version: 0.19
PHP version: 5.4
License: GNU General Public License (GPL)
All time users: 661 users
All time rank: 4804
Week users: 2 users
Week rank: 110 Up
 
  Groups   Rate classes User ratings   Applications   Files Files  

  Groups  
Group folder image PHP 5 Classes using PHP 5 specific features View top rated classes
Group folder image Math Math related classes. View top rated classes


  User ratings  
Not yet rated by the users

  Applications that use this package  
No pages of applications that use this class were specified.

Add link image If you know an application of this package, send a message to the author to add a link here.

  Files folder image Files  
File Role Description
Files folder imagesrc (1 directory)
Files folder imagetests (2 files)
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file code-of-conduct.md Data Auxiliary data
Accessible without login Plain text file code-of-conduct.ru.md Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file LICENSE Data Auxiliary data
Accessible without login Plain text file phpunit.xml.dist Data Auxiliary data
Accessible without login Plain text file README.md Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
Files folder imageNXP (1 file, 2 directories)

  Files folder image Files  /  src  /  NXP  
File Role Description
Files folder imageClasses (5 files)
Files folder imageException (7 files)
  Plain text file MathExecutor.php Class Class source

  Files folder image Files  /  src  /  NXP  /  Classes  
File Role Description
  Plain text file Calculator.php Class Class source
  Plain text file CustomFunction.php Class Class source
  Plain text file Operator.php Class Class source
  Plain text file Token.php Class Class source
  Plain text file Tokenizer.php Class Class source

  Files folder image Files  /  src  /  NXP  /  Exception  
File Role Description
  Plain text file DivisionByZeroException.php Class Class source
  Plain text file IncorrectBracketsException.php Class Class source
  Plain text file IncorrectExpressionException.php Class Class source
  Plain text file MathExecutorException.php Class Class source
  Plain text file UnknownFunctionException.php Class Class source
  Plain text file UnknownOperatorException.php Class Class source
  Plain text file UnknownVariableException.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Accessible without login Plain text file bootstrap.php Test Unit test script
  Accessible without login Plain text file MathTest.php Test Unit test script

Install with Composer Install with Composer - Download Download all files: math-executor.tar.gz math-executor.zip
NOTICE: if you are using a download manager program like 'GetRight', please Login before trying to download this archive.

For more information send a message to info at phpclasses dot org.