TL;DR
+=
appends the value, so the values continuously add up. =
overwrites.
+=
indicates adding the current value of the variable, along with the new value on the right hand side of the argument. a+=b
is simply a=a+b
, which helps make code more succinct.
Inside the loop, you are continuously setting txt
to the current value. Eventually, the last cycle of the loop is on the last item of the array, therefore txt
is the last value.
You can think of it this way:
Inside the loop, you set the variable to the current item. You first go to the first one, and the variable is set to the first one. You go to the second item, and the variable is set to the second item. Eventually, you go to the last item, and the variable is set to the last item.
If you use +=
, you can think of it this way:
Inside the loop, you add the new item to what the variable already was. You first go to the first one, and you add the first item to "". You go to the second one, and you add the second one to the first one etc,. Once you reach the last item, you have added the second last, third last all the way to the first.