NeuroAgent

How to calculate mathematical expressions in PHP

Ready-made libraries and functions for calculating mathematical expressions from strings in PHP. Secure solutions with support for operators + - * / ^ ( ) %.

Question

How to calculate the result of mathematical operations presented as a string?

Is there a ready-made library or function for solving this problem? For example, for the expression:

php
$t = '5 + ( 10 - 2 ) ^ 2 % 10 * 2';
$t = math($t);
echo $t; //13

It is necessary to find a solution that supports the following arithmetic operators:

      • / ^ ( ) %
NeuroAgent

Calculating Mathematical Operations from Strings in PHP

For calculating mathematical operations presented as strings in PHP, there are several ready-made libraries and functions. One of the most popular is the madorin/matex library, which supports all the specified arithmetic operators: + - * / ^ ( ) %, works with variables and functions, and ensures safe expression evaluation.

Contents

matex library

The madorin/matex library is one of the most complete and convenient solutions for your task. It supports all necessary operators and has a compact codebase.

Installation and usage

First, install the library via Composer:

bash
composer require madorin/matex

Usage example

php
<?php
require 'vendor/autoload.php';

use Matex\Evaluator;

$evaluator = new Evaluator();
$evaluator->variables = []; // variables can be predefined

$result = $evaluator->execute('5 + ( 10 - 2 ) ^ 2 % 10 * 2');
echo $result; // outputs 13
?>

Main features

  • Support for operators: + - * / ^ %
  • Support for parentheses: nested, with unlimited levels
  • Variable handling: predefined or dynamic
  • Function support: built-in or custom
  • Fast computation
  • Compact codebase

As noted in the library documentation, it’s perfectly suited for your task and ensures safe expression evaluation.

mossadal/math-parser library

Another excellent solution is the mossadal/math-parser library, which provides a parser and evaluator for mathematical expressions in PHP.

Installation

bash
composer require mossadal/math-parser

Usage example

php
<?php
require 'vendor/autoload.php';

use MathParser\StdMathParser;
use MathParser\Interpreters\Evaluator;

$parser = new StdMathParser();
$AST = $parser->parse('5 + ( 10 - 2 ) ^ 2 % 10 * 2');

$evaluator = new Evaluator();
$value = $AST->accept($evaluator);

echo $value; // 13
?>

Library features

As noted in the official description, this library:

  • Is designed for safe and efficient evaluation of user formulas
  • Supports basic arithmetic and elementary functions
  • Works with variables and additional functions
  • Produces an abstract syntax tree (AST)
  • Has three interpreters: evaluator, differentiator, and simplifier

Other solutions

PHP Classes Math Expression Evaluator

On PHP Classes, there’s a class for parsing and evaluating strings with mathematical expressions. It can be extended to handle new operations.

StringCalc

The StringCalc library is a zero-dependency calculator for mathematical expressions passed as strings.

evaluate_math_string function

On GitHub, there’s a simple function for evaluating math strings without additional dependencies.


Safe usage

When working with user mathematical expressions, security is important. PHP’s standard eval() function is unsafe as it allows execution of arbitrary PHP code.

Example of unsafe usage:

php
// DO NOT USE THIS!
$t = '5 + ( 10 - 2 ) ^ 2 % 10 * 2';
$result = eval("return $t;");

The libraries mentioned above ensure security by allowing only mathematical expressions to be evaluated without the possibility of executing arbitrary code.


Implementation examples

Complete example with matex

php
<?php
require 'vendor/autoload.php';

use Matex\Evaluator;

function math($expression) {
    $evaluator = new Evaluator();
    return $evaluator->execute($expression);
}

// Usage
$t = '5 + ( 10 - 2 ) ^ 2 % 10 * 2';
$t = math($t);
echo $t; // 13

// Other examples
echo math('2 ^ 3 + 4 * 5'); // 28
echo math('(10 + 5) % 7'); // 1
echo math('100 / (2 + 3)'); // 20
?>

Example with mossadal/math-parser

php
<?php
require 'vendor/autoload.php';

use MathParser\StdMathParser;
use MathParser\Interpreters\Evaluator;

function math($expression) {
    $parser = new StdMathParser();
    $AST = $parser->parse($expression);
    $evaluator = new Evaluator();
    return $AST->accept($evaluator);
}

$t = '5 + ( 10 - 2 ) ^ 2 % 10 * 2';
echo math($t); // 13
?>

Sources

  1. madorin/matex - PHP Mathematical expression parser and evaluator
  2. madorin/matex - Packagist
  3. mossadal/math-parser - PHP parser for mathematical expressions
  4. mossadal/math-parser - Packagist
  5. PHP Math Expression Evaluator - PHP Classes
  6. Math Parser for PHP - Math Parsers
  7. StringCalc - Zero-dependency PHP calculator library
  8. evaluate_math_string - Simple PHP function

Conclusion

  • For evaluating mathematical expressions from strings in PHP, there are several ready-made libraries, the most popular of which are matex and mossadal/math-parser
  • The matex library provides support for all necessary operators (+ - * / ^ ( ) %) and has a compact codebase
  • The mossadal/math-parser library creates an abstract syntax tree and provides additional capabilities for mathematical operations
  • Using specialized libraries is preferable to PHP’s built-in eval() function as it ensures security
  • For your task with the expression '5 + ( 10 - 2 ) ^ 2 % 10 * 2', any of the mentioned libraries will return the correct result - 13
  • It’s recommended to install libraries via Composer for convenient dependency management