ktm
ktm

Reputation: 6085

what is the different between this in php?

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

Upvotes: 1

Views: 59

Answers (4)

John
John

Reputation: 16007

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.

Upvotes: 0

Martijn
Martijn

Reputation: 12102

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;

Upvotes: 1

GrandmasterB
GrandmasterB

Reputation: 3455

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.

Upvotes: 0

efritz
efritz

Reputation: 5203

+= 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.

Upvotes: 3

Related Questions