Hi I'm struggling trying to perform a calculation in Laravel 7.
I have a variable like $val = '1000*2';
and I'm looking for a helper function or related to perform it.
eval($val)
does not seem to function in a proper way. I just want a function that results in 2000
.
TIA
CodePudding user response:
If you only have to deal with multiplication, you could try something like this.
$val = '1000*2';
$parts = explode('*', $val);
$res = array_reduce($parts, function($carry, $item) {
return $carry * $item;
}, 1);
echo $res;
CodePudding user response:
I do not advise using eval() to perform calculations with values passed by a user.
If you really want to receive the value at all costs, you can do something like this:
$val = "echo 1000 * 2;";
eval ($val);
Or
$val = eval("return 1000 * 2;");
echo $val;
You can find more information in the documentation. https://www.php.net/manual/pt_BR/function.eval.php
CodePudding user response:
Guys this library helped me https://github.com/mossadal/math-parser
$parser = new StdMathParser();
$AST = $parser->parse($val);
Then I could access it with $AST->getValue()
.
Thank you!!