Home > Back-end >  PHP array sum up session value not adding item after removing comma
PHP array sum up session value not adding item after removing comma

Time:05-30

I am trying to add up the sum of an array of prices with the below code:


 foreach ($_SESSION['cart'] as $item) {
    $sum  = str_replace(",", "", $item['price']);
    echo $sum;                   
}

$item['price'] in above is 10,000 and 5,000 and I used str_replace to remove the comma and sum the values up with = but instead of echo $sum to give 15000 it is giving 1000015000 and I'm not sure where I got it wrong.

CodePudding user response:

Your code works. The problem isn't your values or your =. The problem is that you're echoing the sum inside the foreach, which means that you first add 10000, which you echo. Then add 5000, which will give you 15000, which you then echo after the first 10000 you've already echoed.

Just put the echo after the foreach and you're set.

foreach ($_SESSION['cart'] as $item) {
    $sum  = str_replace(",", "", $item['price']);
}
echo $sum;                   

CodePudding user response:

Try this one:

 foreach ($_SESSION['cart'] as $item) {
    $sum  = intval(str_replace(",", "", $item['price']));                
 }
 echo $sum;   
  • Related