StratHaxxs StratHaxxs - 5 months ago 12x
PHP Question

PHP Eval variable and set another variable

If I have a string like this:


I need it do actually do the math.

So if
$a = '0+1+0+0+0+0+0+1'

It would set another variable and set it as:



You should never eval strings if you can help it. There's a trivial sane solution for parsing and summing this particular string:

$string = '0+1+...';
$result = array_sum(explode('+', $string));

If you want to support more possible operations than just +, you'd do a slightly more complex preg_split, then loop over the resulting items and evaluate each individual operator and sum or subtract or whatever based on the encountered operator in a loop.