StratHaxxs StratHaxxs - 7 months ago 27
PHP Question

PHP Eval variable and set another variable

If I have a string like this:

0+1+0+0+0+0+0+1+0+1+1+1+1+0+0+1+0+1+1+1+1+0+0+1+0+0+1+0+0+0+0+0+0+1+1+0+1+1+0+0+0+1+1+0+1+1+0+1+0+1+1+0+0+0+0+1+0+1+1+0+1+1+1+1



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:

2

Answer

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.