tags:

views:

22

answers:

4

Hi friends what is the difference between

$totalprice += $product['price'] * $product['count'];

and

$totalprice = $product['price'] * $product['count'];

both give the same result. so what's the use of (+=) ?

+3  A: 

+= is a shorthand for adding the result to the target. The first one is equivalent to:

$totalprice = $totalprice + ($product['price'] * $product['count']);

There are also other compound operators -=, *=, /=, etc.

efritz
@sagarmatha you're getting the same result because `$totalprice` is presumably currently 0, but you're doing the extra processing. If you have globals auto-register, or set this value somewhere else, that value could change.
Rudu
A: 

The += takes $totalprice and adds $product['price'] * $product['count'] to it. The = asigns the value of $product['price'] * $product['count'] to $totalprice.

If you are getting the same result, its because $totalprice started off equal to 0.

GrandmasterB
+1  A: 

They only give the same result if $totalprice starts off at 0 or uninitialised

The += syntax is shorthand for the following:

$myvar += a;

is equivalent to

$myvar = $myvar + a;
Martijn
A: 

If $totalprice is zero to start, then they're the same. Otherwise, they're different.

As others have pointed out, $i += $j is shorthand for $i = $i + $j.

John at CashCommons