StratHaxxs
StratHaxxs

Reputation: 61

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

Upvotes: 1

Views: 251

Answers (2)

deceze
deceze

Reputation: 522606

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.

Upvotes: 3

Imesha Sudasingha
Imesha Sudasingha

Reputation: 3570

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

Upvotes: 0

Related Questions