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
?>
3
  • 3
    You could use eval, but mind you, this comes with serious security issues. Commented Aug 13, 2018 at 6:32
  • 4
    Possible duplicate of How to evaluate formula passed as string in PHP? Commented Aug 13, 2018 at 6:35
  • In this question eval is probably the right answer, however this does feel like an XY problem question Commented Aug 13, 2018 at 12:30

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
Be aware that the example code on the github page misses the mandatory require 'vendor/autoload.php';
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().

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.