3

I've got field in my database which contain strings like 21;48;33;22;31. Then I'd like to convert it to mathematical calculation 21+48+33+22+31.

$points = "21;48;33;22;31"; $points = str_replace(";","+",$points ); $points = preg_replace('/[^0-9\+\-\*\/\s]+/', '', $points); echo $points; 

But that simply does not work. I've got the same string "21+48+33+22+31" instead of the sum.

2
  • 6
    Split up the string by using explode, and then calculate the sum: array_sum(explode(';', $points)); Commented Mar 25, 2013 at 9:03
  • 2
    That's because you never calculate it... Commented Mar 25, 2013 at 9:03

6 Answers 6

8
$points = "21;48;33;22;31"; $points = explode(';',$points ); $points = array_sum($points); echo $points; 
Sign up to request clarification or add additional context in comments.

Comments

2
$points = "21;48;33;22;31"; $arr = explode(";", $points); $points = 0; foreach($arr as $key => $rows){ $points += $rows[$key]; } echo $points; 

Try above code it will give you proper result.

or you can try it also:

$points = "21;48;33;22;31"; $arr = explode(";", $points); echo $points = array_sum($arr); 

Comments

0

The easiest way is to explode the string.

Then you can iterate with foreach over the resulting array and calculate them.

$points = "21;48;33;22;31"; $points = explode(";", $points); $calc = 0; forearch($points as $point) { $calc += $point; } 

Or your can use array_sum:

$points = "21;48;33;22;31"; $points = explode(";", $points); $calc = array_sum($points); 

Something like that. Perhaps there are some shorter ways.

Comments

0
$string = "21;48;33;22;31"; $string = explode(";" , "21;48;33;22;31"); $point = 0; foreach($string as $num) { // by using (int) you can convert string to int. $point = (int)$num + $point; } print($point); // output 155 

Comments

0

explode it then loop for sum...

 <?php $total = 0; // for getting the total $points = "21;48;33;22;31"; $points = explode(';',$points); for($i=0;$i<count($points);$i++){ $total+= $points[$i]; } echo $total; ?> 

Comments

0
<?php eval('$sum = ' . str_replace(';','+','21;48;33;22;31').';'); echo $sum; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.