Math Parser for PHP

Interpreted languages make it easy to evaluate code typically via their eval() function. But if you have ever tried to use it, in PHP you have noticed that it is unsafe to call eval to evaluate a string given by the user. To work around this problem we felt the need to implement a parser in PHP to parse and evaluate mathematical expressions that is isolated from the PHP runtime functions.

PHP formula parser

bcParserPHP, the PHP Math Parser comes as a single file source code that can easily be integrated into your PHP applications.


bcParserPHP Math Parser for PHP library parses and evaluates formulas given as strings at runtime. You can define variables, you can define custom functions that can be used in the expression. The user cannot call any other PHP function that you have not defined and registered with a parser instance.
 
 
 
Here is a simple example of using the math parser library:

   include('mathparser/mathparser.php');
   $parser = new MathParser();
   $parser->setVariable('X', 3);
   $parser->setVariable('Y', 4);
   $parser->setExpression('COS(X)+SIN(Y)/2');
   echo $parser->getValue();

The Math Parser features highlights are as follows:

  • Easy to use, simple PHP class API.
  • Functions with 0 or more known number of parameters in the form of: f(x,y,z)
  • Functions with unknown number of parameters, e.g. SUM(a,b,c,…)
  • Comes with predefined math functions.
  • You can create custom functions/variables with callbacks to the functions that you define in your source code.
  • VariableResolver, a callback function to provide values for undefined variables.
  • Function/variable names start with letters and can contain letters, numbers and underscore (_).
  • Expression can contain string literals, variable values and function return values can be strings.
  • Arithmetic Operators: +, -, /, *, ^, %(mod)
  • Boolean Operators: <, >, =, &, |, ! ,<>, >=, <=
  • String concatenation with & or +
  • Optimization: Constant expression elimination for repeated tasks.
  • Paranthesis: ( )
  • Provides localization support which is a dictionary of message-keys to messages you can set.
  • Royalty free distribution.
  • Comes as source code.

You can parse an expression once, and then evaluate it for different variable values many times:

   $parser = new MathParser();
   $parser->setExpression('X+Y/2');
   try {
      // parse the expression once:
      $parser->parse();
      for ($i = 0; $i < 10; $i++) {
         $parser->setVariable('X', $i);
         $parser->setVariable('Y', $i*3);
         // evaluate many times for different variables:
         $result = $parser->getValue();
         // do something with result
      }
   } catch (MathParser_ParserException $ex) {
      // Expression is not valid:
      print($ex->getMessage()."\n");
   }

How to Use a Variable Resolver

If you don’t know what variables the user might use, then you can use VariableResolver callback function that you register via setVariableResolver function.
A variableResolver callback function looks like this:

function variableResolver($parser, $varName) {
    if($varName==('K')){
        return 5; // this is a simple example.
        // In reality, you could do fancy things like on the fly computations,
        // or database lookups.
    }
    throw new Exception('Unknown variable name: '.$varName);
}

then you could do:

$varRes = 'variableResolver';
$parser->setVariableResolver($varRes);
$parser->setExpression('3+ K');
echo $parser->getValue();

In above code, even though you did not explicitly set the value of variable K (variable was never defined), the variableResolver function that you register will return a value for it at runtime.

User Defined Functions

   include('mathparser/mathparser.php');
   $parser = new MathParser();
   $parser->createFunc('MYFUNC', 'any_php_func_with_one_param', 1);
   $parser->setExpression('MYFUNC(3)+1');
   echo $parser->getValue(); // prints 7
   // the implementation of your function is something like:
   function any_php_func_with_one_param($p) {
     return $p * 2;
   } 

Functions that take any number of parameters

   include('mathparser/mathparser.php');
   $parser = new MathParser();
   $parser->createFunc('MULTIPLY', 'multiply_func', -1); // -1 means any number of params
   $parser->setExpression('MULTIPLY(2,3,4)+1');
   echo $parser->getValue(); // prints 25
   // the implementation of your function is something like:
   function multiply_func() {
     $p = func_get_args();
     $count = func_num_args();
     $tot=1;
     for($i=0; $i<$count; $i++){
          $tot*=$p[$i];
     }
     return $tot;
   } 

bcParserPHP Math Parser for PHP Documentation

You can view online documentation for Math Parser for PHP here.

bcParserPHP Math Parser for PHP Trial Version

Math Parser for PHP comes as PHP source code. Therefore, we do not have a binary version that you can download and try. However, we do have a PHP page where you can enter a simple math expression and submit it to be evaluated by a a PHP script that is using the Math Parser Library. You may access that Math Parser evaluation page here.

bcParserPHP Math Parser Library Licensing

Once purchased, Math Parser comes with a royalty free license to develop and deploy your applications. Math Parser pricing is based on number of developers who will use it. There is also site license available for bigger organizations. The Math Parser Library license can be viewed here.

Purchasing bcParserPHP Math Parser for PHP Library

You can pay with credit card and download Math Parser for PHP immediately from our online store for only $29.95. The download includes PHP source code. Upgrades are free for registered users. Licensing is per developer. You can deploy the the library royalty free with your applications as many times as you want. Site license allows any number of developers use the component at your development site. Site License is $290.95. Site licenses can be purchased here.

Online Order Form