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:

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

But realised that it also works like this:

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

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

Thanks

Answers


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

Search




Leave an answer