StratHaxxs StratHaxxs - 2 years ago 90
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:


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download