开发者

what is the different between this in php?

开发者 https://www.devze.com 2023-01-13 21:13 出处:网络
what is the difference between $totalprice += $product[\'price\'] * $product[\'开发者_JS百科count\'];

what is the difference between

$totalprice += $product['price'] * $product['开发者_JS百科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.


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;


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消