I have a variable e.g. $number="1+2+3" but I want to change the variable to $number=6 or "6" by doing the math inside the string
Five answers:
what?
2009-06-20 08:58:26 UTC
I don't write a lot of PHP for some syntax might be off, but I would look up the preg_split() function, below is an example that may work. It splits the numbers string into parts separated by the + sign.
$number = "1+2+3";
$numbers = preg_split("+",$number);
$sum = 0;
for($i = 0; $i < $numbers; $i++){
.....$sum += (int)$numbers[i];
}
$sum whould now equal 6
Josh
2009-06-20 23:53:33 UTC
Technically you could do this with php's eval() function. However if the string is text coming from a user then this would create a big security problem because it would let the user run any php code: http://ca.php.net/manual/en/function.eval.php
You may want to take a look at this class on phpclasses.org which claims to solve this problem: