Reputation: 1598
I am trying to add up the price in my foreach loop to give me an overall total. I am struggling as I can only get the first value:
$sum = 0;
foreach ($_SESSION['products'] as $product) {
$name = $product['name'];
$id = $product['id'];
$price = $product['price'];
$img = $product['img'];
$sku = $product['sku'];
$description = $product['description'];
echo '<a href="single_product.php?product_id=' . $product['id'] . '">';
echo "<img src='$img'><br />";
echo "Product: $name<br />";
echo "Price: $price | ID: $id<br />";
echo "$description";
echo '</a>';
echo '<br /><br />';
$sum += $price;
}
echo $price;
I have probably gone about this the wrong way but looking online keep telling me the same approach but I am confused:
Upvotes: 0
Views: 839
Reputation: 5049
echo $sum
instead of $price
outside of loop, as you are storing total in $sum
$sum = 0;
foreach ($_SESSION['products'] as $product) {
...
$price = $product['price'];
...
$sum += $price;
}
echo $sum; // echo $sum over here
Upvotes: 3