Staysee
Staysee

Reputation: 1907

Displaying the sum of a foreach loop

I have a table like this: id | item_name | price

I have a loop that displays all items with the grand total at the bottom.

$total_price = 0;

foreach($items as $item)
{
    echo $item->item_name;
    echo $item->price;

    $total_price += $item->price;
}

echo $total_price;

However, what I need is to display the $total_price at the TOP of the page, before I loop through all the items.

Is it better to loop through the foreach again at the top of the page to calculate the total price, or should I be making a separate database call that only returns the total price?

Upvotes: 0

Views: 296

Answers (3)

newage
newage

Reputation: 909

It's simple and fast decision

$total_price = 0;
$print = '';
foreach($items as $item)
{
    $print .= $item->item_name;
    $print .= $item->price;

    $total_price += $item->price;
}

echo $total_price;
echo $print;

If you can get sum from SQL base it will be more best solution. In MySQL use function SUM()

Example:

SELECT SUM(price) AS total FROM ...

Upvotes: 3

akazakou
akazakou

Reputation: 195

Maybe you need use MySQL query like this:

SELECT SUM(price) FROM your_table

Upvotes: 0

ztripez
ztripez

Reputation: 664

This is one of the reasons why you should never mix php code and direct output. I would suggest you look into one of the template engines for php.

Unless you are writing php-cli do all the operations before you start to output. This will increase the flexibility of your code a lot.

Smarty is one of my favourite tempelate engines, easy to setup and with powerfull features, but that's my opinion.

Upvotes: 0

Related Questions