简体   繁体   中英

Sum two array values in php

I have two cookies and their values like this:

foreach($_COOKIE as $key=>$val) {
    $piece = explode(",", $val);
    $t_cost = array($piece[3]);
    print_r($t_cost); //It prints Array ( [0] => 11 ) Array ( [0] => 11 )
    echo $total_cost = array_sum($t_cost);
}

But it prints only one value. How can I add the both values to sum them?

I think you don't need array_sum, just use += operator it will save a bit of memory

$t_cost = 0;
foreach($_COOKIE as $key=>$val) {
    $piece = explode(",", $val);
    $t_cost += $piece[3];
}
echo $t_cost;

There is no need of array_sum actually.

// the array where all piece[3] values are stored
$t_cost = array();

// loop through array
// just foreach($_COOKIE as $val) is enough
foreach($_COOKIE as $key=>$val) {

    // split by comma
    $piece = explode(",", $val);

    // add to array
    $t_cost[] = $piece[3];

}
// sum up  
$total_cost = array_sum($t_cost);   

or just

$total = 0;
foreach($_COOKIE as $key=>$val) {
        $piece = explode(",", $val);  
        $total += $piece[3];
}
echo $total;
$total = 0;
foreach($_COOKIE as $key=>$val) {
      $piece = explode(",", $val);
      $t_cost = trim(str_replace('$', '', array($piece[3]));
      $total += (float)$t_cost;
      echo "The total cost: $".$total;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM