Home Ask Login Register

Developers Planet

Your answer is one click away!

Ahmed February 2016

adding variable numbers in PHP loop counter

I've got a PHP loop and a counter called $total which is set to 0 before the loop. Then once the loop starts I am adding the value of $weight to the loop counter. I originally did it like this:

foreach ($weights as $weight){
    $total = $total+$weight;

But realised that it also works like this:

foreach ($weights as $weight){
    $total += $weight;

Question is which is the correct method or if both are correct which is the better method?



Ed Cottrell February 2016

Both are correct, and neither is better, strictly speaking. They function identically.

That said, some coding styles prefer += because it's easier to read, while others prefer $x = $x + $y because it requires more deliberate action to write, makes more obvious what is happening, and reduces the likelihood of a single-character typo.

Post Status

Asked in February 2016
Viewed 2,568 times
Voted 13
Answered 1 times


Leave an answer

Quote of the day: live life