Reputation:
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
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
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
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