Question:
How do I calculate this string with php?
foddski
2009-06-20 06:40:24 UTC
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:

http://www.phpclasses.org/browse/package/2695.html
anonymous
2009-06-23 11:06:10 UTC
$number = "1+2+3" is a string and will not calculate on its own



$add_em = explode("+", $numbers);

echo array_sum($add_em);
?
2009-06-23 00:13:06 UTC
You can use the php's eval() function. Judging by what you just described, I think eval function should be sufficient. The function is documented at:



http://www.php.net/eval
Webmaster H
2009-06-20 07:56:00 UTC
What do you mean?


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...