{"id":22446779,"url":"https://github.com/neonxp/mathexecutor","last_synced_at":"2025-05-14T20:10:46.483Z","repository":{"id":7427963,"uuid":"8764639","full_name":"neonxp/MathExecutor","owner":"neonxp","description":"Simple math expresions parser and calculator","archived":false,"fork":false,"pushed_at":"2025-02-17T19:42:07.000Z","size":244,"stargazers_count":212,"open_issues_count":0,"forks_count":50,"subscribers_count":14,"default_branch":"master","last_synced_at":"2025-04-13T17:46:42.758Z","etag":null,"topics":["expression","expression-evaluator","math","mathematics","php"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/neonxp.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":"code-of-conduct.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2013-03-14T00:23:19.000Z","updated_at":"2025-03-31T13:07:23.000Z","dependencies_parsed_at":"2024-02-23T21:27:02.685Z","dependency_job_id":"a1956570-c2a7-42be-a578-f0d8a1e134b1","html_url":"https://github.com/neonxp/MathExecutor","commit_stats":{"total_commits":153,"total_committers":25,"mean_commits":6.12,"dds":0.5751633986928104,"last_synced_commit":"e1cca194c57cf242fd8635b2e72e11e990279c95"},"previous_names":[],"tags_count":45,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neonxp%2FMathExecutor","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neonxp%2FMathExecutor/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neonxp%2FMathExecutor/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neonxp%2FMathExecutor/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/neonxp","download_url":"https://codeload.github.com/neonxp/MathExecutor/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254219374,"owners_count":22034397,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["expression","expression-evaluator","math","mathematics","php"],"created_at":"2024-12-06T04:11:19.275Z","updated_at":"2025-05-14T20:10:46.464Z","avatar_url":"https://github.com/neonxp.png","language":"PHP","readme":"# MathExecutor [![Tests](https://github.com/neonxp/MathExecutor/workflows/Tests/badge.svg)](https://github.com/neonxp/MathExecutor/actions?query=workflow%3ATests) ![](https://img.shields.io/badge/PHPStan-level%206-brightgreen.svg?style=flat)\n\n# A simple and extensible math expressions calculator\n\n## Features:\n* Built in support for +, -, *, /, % and power (^) operators\n* Parentheses () and arrays [] are fully supported\n* Logical operators (==, !=, \u003c, \u003c, \u003e=, \u003c=, \u0026\u0026, ||, !)\n* Built in support for most PHP math functions\n* Support for BCMath Arbitrary Precision Math\n* Support for variable number of function parameters and optional function parameters\n* Conditional If logic\n* Support for user defined operators\n* Support for user defined functions\n* Support for math on user defined objects\n* Dynamic variable resolution (delayed computation)\n* Unlimited variable name lengths\n* String support, as function parameters or as evaluated as a number by PHP\n* Exceptions on divide by zero, or treat as zero\n* Unary Plus and Minus (e.g. +3 or -sin(12))\n* Pi ($pi) and Euler's number ($e) support to 11 decimal places\n* Easily extensible\n\n## Install via Composer:\n```\ncomposer require nxp/math-executor\n```\n\n## Sample usage:\n```php\nuse NXP\\MathExecutor;\n\n$executor = new MathExecutor();\n\necho $executor-\u003eexecute('1 + 2 * (2 - (4+10))^2 + sin(10)');\n```\n\n## Functions:\nDefault functions:\n* abs\n* acos (arccos)\n* acosh\n* arccos\n* arccosec\n* arccot\n* arccotan\n* arccsc (arccosec)\n* arcctg (arccot, arccotan)\n* arcsec\n* arcsin\n* arctan\n* arctg\n* array\n* asin (arcsin)\n* atan (atn, arctan, arctg)\n* atan2\n* atanh\n* atn\n* avg\n* bindec\n* ceil\n* cos\n* cosec\n* cosec (csc)\n* cosh\n* cot\n* cotan\n* cotg\n* csc\n* ctg (cot, cotan, cotg, ctn)\n* ctn\n* decbin\n* dechex\n* decoct\n* deg2rad\n* exp\n* expm1\n* floor\n* fmod\n* hexdec\n* hypot\n* if\n* intdiv\n* lg\n* ln\n* log (ln)\n* log10 (lg)\n* log1p\n* max\n* median\n* min\n* octdec\n* pi\n* pow\n* rad2deg\n* round\n* sec\n* sin\n* sinh\n* sqrt\n* tan (tn, tg)\n* tanh\n* tg\n* tn\n\nAdd custom function to executor:\n```php\n$executor-\u003eaddFunction('concat', function($arg1, $arg2) {return $arg1 . $arg2;});\n```\nOptional parameters:\n```php\n$executor-\u003eaddFunction('round', function($num, int $precision = 0) {return round($num, $precision);});\n$executor-\u003eexecute('round(17.119)'); // 17\n$executor-\u003eexecute('round(17.119, 2)'); // 17.12\n```\nVariable number of parameters:\n```php\n$executor-\u003eaddFunction('average', function(...$args) {return array_sum($args) / count($args);});\n$executor-\u003eexecute('average(1,3)'); // 2\n$executor-\u003eexecute('average(1, 3, 4, 8)'); // 4\n```\n\n## Operators:\nDefault operators: `+ - * / % ^`\n\nAdd custom operator to executor:\n\n```php\nuse NXP\\Classes\\Operator;\n\n$executor-\u003eaddOperator(new Operator(\n    '%', // Operator sign\n    false, // Is right associated operator\n    180, // Operator priority\n    function (\u0026$stack)\n    {\n       $op2 = array_pop($stack);\n       $op1 = array_pop($stack);\n       $result = $op1-\u003egetValue() % $op2-\u003egetValue();\n\n       return $result;\n    }\n));\n```\n\n## Logical operators:\nLogical operators (==, !=, \u003c, \u003c, \u003e=, \u003c=, \u0026\u0026, ||, !) are supported, but logically they can only return true (1) or false (0).  In order to leverage them, use the built in **if** function:\n\n```\nif($a \u003e $b, $a - $b, $b - $a)\n```\n\nYou can think of the **if** function as prototyped like:\n\n```\nfunction if($condition, $returnIfTrue, $returnIfFalse)\n```\n## Variables:\nVariables can be prefixed with the dollar sign ($) for PHP compatibility, but is not required.\n\nDefault variables:\n\n```\n$pi = 3.14159265359\n$e  = 2.71828182846\n```\n\nYou can add your own variables to executor:\n\n```php\n$executor-\u003esetVar('var1', 0.15)-\u003esetVar('var2', 0.22);\n\necho $executor-\u003eexecute(\"$var1 + var2\");\n```\n\nArrays are also supported (as variables, as func params or can be returned in user defined funcs):\n```php\n$executor-\u003esetVar('monthly_salaries', [1800, 1900, 1200, 1600]);\n\necho $executor-\u003eexecute(\"avg(monthly_salaries) * min([1.1, 1.3])\");\n```\n\nBy default, variables must be scalar values (int, float, bool or string) or array.  If you would like to support another type, use **setVarValidationHandler**\n\n```php\n$executor-\u003esetVarValidationHandler(function (string $name, $variable) {\n    // allow all scalars, array and null\n    if (is_scalar($variable) || is_array($variable) || $variable === null) {\n        return;\n    }\n    // Allow variables of type DateTime, but not others\n    if (! $variable instanceof \\DateTime) {\n        throw new MathExecutorException(\"Invalid variable type\");\n    }\n});\n```\n\nYou 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.\n\n```php\n$calculator = new MathExecutor();\n$calculator-\u003esetVarNotFoundHandler(\n    function ($varName) {\n        if ($varName == 'trans') {\n            return transmogrify();\n        }\n        return null;\n    }\n);\n```\n\n## Floating Point BCMath Support\nBy 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.\n`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.\n\n## Division By Zero Support:\nDivision by zero throws a `\\NXP\\Exception\\DivisionByZeroException` by default\n```php\ntry {\n    echo $executor-\u003eexecute('1/0');\n} catch (DivisionByZeroException $e) {\n    echo $e-\u003egetMessage();\n}\n```\nOr call setDivisionByZeroIsZero\n```php\necho $executor-\u003esetDivisionByZeroIsZero()-\u003eexecute('1/0');\n```\nIf you want another behavior, you can override division operator:\n```php\n$executor-\u003eaddOperator(\"/\", false, 180, function($a, $b) {\n    if ($b == 0) {\n        return null;\n    }\n    return $a / $b;\n});\necho $executor-\u003eexecute('1/0');\n```\n\n## String Support:\nExpressions 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.\n\n```php\necho $executor-\u003eexecute(\"1 + '2.5' * '.5' + myFunction('category')\");\n```\nTo use reverse solidus character (\u0026#92;) 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 (\u0026#92;).\n\n```php\necho $executor-\u003eexecute(\"countArticleSentences('My Best Article\\'s Title')\");\n```\n\n## Extending MathExecutor\nYou 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:\n* defaultOperators\n* defaultFunctions\n* defaultVars\n\nThis will allow you to remove functions and operators if needed, or implement different types more simply.\n\nAlso 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 '\\\\+'.\n\n## Documentation\n\nFull class documentation via [PHPFUI/InstaDoc](http://phpfui.com/?n=NXP\u0026c=MathExecutor)\n\n## Future Enhancements\n\nThis package will continue to track currently supported versions of PHP.\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneonxp%2Fmathexecutor","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fneonxp%2Fmathexecutor","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneonxp%2Fmathexecutor/lists"}