After a lot of operations I've got some like:
$exr = "2+3/1.5";
How I can get result of this expression? Like this:
$result = (floatval)$exr; // show: 4
Of course it doesn't work. I've got only 2, first symbol. Any easy way to solve this?
After a lot of operations I've got some like:
$exr = "2+3/1.5";
How I can get result of this expression? Like this:
$result = (floatval)$exr; // show: 4
Of course it doesn't work. I've got only 2, first symbol. Any easy way to solve this?
You can use the PHP eval
function like this:
$exr = '2+3/1.5';
eval('$result = ' . $exr . ';');
var_dump($result);
// float(4)
Read this note carefully:
Caution: The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.
I dont know why every answer here is telling you to do this? But avoid using this.
Here is very good function that can do the same without the eval() Source
function calculate_string( $mathString ) {
$mathString = trim($mathString); // trim white spaces
$mathString = ereg_replace ('[^0-9\+-\*\/\(\) ]', '', $mathString); // remove any non-numbers chars; exception for math operators
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
Use it as
$exr = '2+3/1.5';
echo calculate_string($exr);
Try:
$exr = "2+3/1.5";
echo eval("return $exr;"); //shows 4
The easiest way would be to just run it through eval(), but that is very insecure. For security I'd recommend to filter certain characters, like a-z and special chars like ";:'.