TheBlackBenzKid
TheBlackBenzKid

Reputation: 27087

Add numbers in foreach Loop PHP

I have a foreach loop which lists through a number of products in OpenCart. I want to return the total in a variable called $subTotal - however it only returns the last product price, should it be =+ or +++ all return errors.

Update - I should add that $product['total'] alone will echo £100 for example (not £100 it just echos the currency symbol and numeric)

<?
####
// START ***********
####
$subTotal=0;
foreach ($products as $product) {
    $subTotal=$product['total'];
?>

 <!--<?=$product['total']?>-->

<?
    $subTotal++;
}
####
// END ***********
####
?>
<?=$subTotal?>

Upvotes: 0

Views: 6427

Answers (5)

dead
dead

Reputation: 364

$subTotal += $product['total'];

Upvotes: 0

donald123
donald123

Reputation: 5739

EDIT

You could do this by

<?php 
// create vars
$x=$product['total'];

// remove pound signs etc
$x=str_replace("£", "", $x);
$x=str_replace("&pound;", "", $x);

// loop and or add to the variable subTotal
$subTotal += $x;

foreach ($products as $product) {
    $subTotal+= preg_replace('/[^\d\.]/','',$product['total']);

}
echo $subTotal;
?>

in your foreach statement

Upvotes: 4

Kirill Speransky
Kirill Speransky

Reputation: 5

foreach ($products as $product) {
    $subTotal += $product['total'];
?>

Upvotes: 0

WhoaItsAFactorial
WhoaItsAFactorial

Reputation: 3558

The issue is that you are setting $subTotal to be equal to $product['total']. You need to add $product['total'] to $subTotal.

foreach ($products as $product) {
    $subTotal=+$product['total']; ?>
} 

Upvotes: -1

MoMo
MoMo

Reputation: 111

Try $subTotal += $product['total'];

Upvotes: 0

Related Questions