user1928251
user1928251

Reputation:

Sum substring values from an array of delimited strings

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?

Upvotes: 3

Views: 2523

Answers (3)

Akshay Hegde
Akshay Hegde

Reputation: 16997

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;

Upvotes: 1

Jeff Mattson
Jeff Mattson

Reputation: 393

$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;
}

Upvotes: 1

AZinkey
AZinkey

Reputation: 5319

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;

Upvotes: 2

Related Questions