1

How do I calculate a math expression in the form of a string to an output using PHP?

<?php
    $ma ="min(2+10,5*1,max(8/2,8-2,abs(-10)))"; // math expression
    print $ma; // output of the calculation
?>
Mark
  • 3,231
  • 3
  • 32
  • 57
Parth Ajudiya
  • 11
  • 1
  • 2
  • 3
    You could use [`eval`](http://php.net/manual/en/function.eval.php), but mind you, this comes with serious security issues. – Bart Friederichs Aug 13 '18 at 06:32
  • 4
    Possible duplicate of [How to evaluate formula passed as string in PHP?](https://stackoverflow.com/questions/1015242/how-to-evaluate-formula-passed-as-string-in-php) – Nigel Ren Aug 13 '18 at 06:35
  • In this question `eval` is probably the right answer, however this does feel like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) question – apokryfos Aug 13 '18 at 12:30

2 Answers2

6

I made a math_eval helper function package that should do exactly want you need.

Example usage:

require 'vendor/autoload.php';

$two   = math_eval('1 + 1');
$three = math_eval('5 - 2');
$ten   = math_eval('2 * 5');
$four  = math_eval('8 / 2');

Link: https://github.com/langleyfoxall/math_eval

In the background, this wraps around the mossadal/math-parser package.

Peter
  • 2,051
  • 1
  • 15
  • 20
DivineOmega
  • 389
  • 1
  • 5
  • 11
  • While this package appears to be good, it’s licenced under LGPL so it will never get the usage it deserves. If it’s not MIT, commercial applications won’t use it. – Savlon Jun 14 '21 at 20:38
  • Be aware that the example code on the github page misses the mandatory `require 'vendor/autoload.php';` – Peter Dec 02 '21 at 07:49
1

I've found some parsers on GitHub, this one looks very interesting:

mossadal/math-parser: PHP parser for mathematical expressions

It can be used this way:

use MathParser\StdMathParser;
use MathParser\Interpreting\Evaluator;

$parser = new StdMathParser();

// Generate an abstract syntax tree
$AST = $parser->parse('1+2');

// Do something with the AST, e.g. evaluate the expression:
$evaluator = new Evaluator();

$value = $AST->accept($evaluator);
echo $value;

It can also be used with functions like cos() or sin().

Chocolord
  • 493
  • 3
  • 12