Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php calculate string values: "2+4+3-12+3-5"

How can I calculate values in a string containing the following numbers and (+/-) operators:

Code Like

$string = "3+5+3-7+4-3-1"; 

//result should be = 4

Updated: I am trying to calculate $array = [1, +, 6, -, 43, +, 10];

I have converted into the string: implode("", $array);

like image 417
Ehtasham Nasir Avatar asked Nov 29 '25 04:11

Ehtasham Nasir


1 Answers

you can use eval

$string = "3+5+3-7+4-3-1"; 
eval( '$res = (' . $string . ');' );
echo $res;
like image 105
sami Avatar answered Nov 30 '25 18:11

sami