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