3

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?

2
  • Push each value ($t_cost) in a new array then apply the array--sum on that array? Commented Oct 6, 2017 at 12:07
  • This question doesn't contain a clear minimal reproducible example. Commented Jan 14, 2024 at 8:55

3 Answers 3

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

How does that work because it works can you explain me?
$key doesn't appear to be useful.
1
$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;
}

1 Comment

This answer is missing its educational explanation.
1

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;

2 Comments

$key doesn't appear to be useful.
@mickmackusa: You're right in current context its not needed, as you can see OP posted problem with foreach ..., I just showed one of possible methods to get required output.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.