Home > Software engineering >  How to sum up value in session - PHP
How to sum up value in session - PHP

Time:04-26

I'm trying to sum up all the values returned from a session but I'm unable to achieve this with array_sum(); but return nothing. Below is what my code looks like:

<?php 
                                        
for($i=0;$i<count($_SESSION['img_src']);$i  ){

    $subTotal = $_SESSION['price'][$i];
    echo $subTotal;

   }
                            
?>

In the above code echo $subTotal; returns 9,999 11,999 9,999 and I tried using echo array_sum($subTotal); but got nothing and I want to be able to get a sum up to be 31,997

CodePudding user response:

You can remove all of the commas in one call:

<?php
$values = array("9,999","11,999","9,999");
$sum = array_sum( str_replace(",", "", $values ));
echo "$sum\n";
?>

Output:

C:\tmp>php x.php
31997

Replace $values with $_SESSION['price'] in your case, of course, so your code ends up as this, and NOTHING more:

<?php
$sum = array_sum( str_replace(",", "", $_SESSION['price']));
echo "$sum\n";
?>
  •  Tags:  
  • php
  • Related