1

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 (+=) ?

ktm
  • 6,025
  • 24
  • 69
  • 95

4 Answers4

3

+= 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
  • 5,125
  • 4
  • 24
  • 33
  • 1
    @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 Sep 01 '10 at 19:44
1

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
  • 11,964
  • 12
  • 50
  • 96
0

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
  • 3,396
  • 1
  • 23
  • 22
0

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
  • 15,990
  • 10
  • 70
  • 110