Sanjay Nakate
Sanjay Nakate

Reputation: 2098

Store loop variable values in single variable in loop

In below, I am displaying the discount using loop $finaltot total displays the value the multiple values that multiple values I have to store in variable with there mathematical addition.

suppose its displaying value 10 23 40 so i have to make like 10 + 23 + 40

so it will display $finaltot=73

so how do I do this within loop.

<?php
    $product_orignalprice = $this->getProduct()->getPrice();
    $discountedprice=$_item->getPrice(); 
    $todatlsaving=$product_orignalprice-$discountedprice;
    echo $finaltot=$todatlsaving * $this->getQty(); 

?>

Upvotes: 1

Views: 526

Answers (1)

Fluffeh
Fluffeh

Reputation: 33512

The quickest/simplest way is to keep adding the data to the variable:

The += sign is used to mean equals whatever it was plus the new value - so writing $var+=$newVar is the same as writing $var=$var+$newVar;

<?php
    $product_orignalprice = $this->getProduct()->getPrice();
    $discountedprice=$_item->getPrice(); 
    $todatlsaving=$product_orignalprice-$discountedprice;
    $finaltot+=$todatlsaving * $this->getQty();
    echo $finaltot;
?>

You could however use an array inside the loop and at the end of that go through and tally up the prices (along with whatever else you needed to do with the array).

You could write a class and keep the data in there using a public function to keep adding to a property of the class.

In programming, there are normally multitudes of ways to do something. Use the most flexible, the one that is easiest to read for others reading your code or one that is most efficient - depending on what you need to achieve.

Edit: If you write the echo statement INSIDE the loop, it will of course show a cumulative total each time the loop runs - in your example it would output 10 23 73. If you run the loop incrementing the variable and then actually echo the final number after the loop you will get what you want.

Upvotes: 2

Related Questions