1

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(); 

?>

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

do you give me any clue for loop incrementing for this question
@SanjayNakate Not sure what you mean here. I am assuming that the code you posted is just the snippet of code from inside a loop you already have to iterate over your database result (or whatever it is you are iterating over)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.