Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String as calculation in php

Tags:

php

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.

like image 291
danny3b Avatar asked Apr 10 '26 00:04

danny3b


2 Answers

$points = "21;48;33;22;31";
$points = explode(';',$points );
$points = array_sum($points);
echo $points;
like image 189
hodl Avatar answered Apr 11 '26 14:04

hodl


$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);
like image 22
Code Lღver Avatar answered Apr 11 '26 13:04

Code Lღver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!