1

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

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this really helps. I know eval is bad, it was the really first solution that came to my mind.
0

You can use the php eval function as follows.

<?php
$string="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";

eval("\$val=$string;");
var_dump($val);
?>

This will output int(31) which is the sum of the integers in the string

1 Comment

lets hope its not a user submitted string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.