What are the differences between .= and += in PHP?
Asked
Active
Viewed 1.7k times
21
-
1silly question... I know. My brain lapsed... lol – Derek Adair Feb 04 '10 at 19:10
-
1Just learning PHP, this is a good question. – TRS7 Jul 27 '18 at 01:07
6 Answers
31
Quite simply, "+=" is a numeric operator and ".=" is a string operator. Consider this example:
$a = 'this is a ';
$a += 'test';
This is like writing:
$a = 'this' + 'test';
The "+" or "+=" operator first converts the values to integers (and all strings evaluate to zero when cast to ints) and then adds them, so you get 0.
If you do this:
$a = 10;
$a .= 5;
This is the same as writing:
$a = 10 . 5;
Since the "." operator is a string operator, it first converts the values to strings; and since "." means "concatenate," the result is the string "105".
![](../../users/profiles/124732.webp)
Brian Lacy
- 17,820
- 9
- 50
- 73
10
The .
operator is the string concatenation operator. .=
will concatenate strings.
The +
operator is the addition operator. +=
will add numeric values.
![](../../users/profiles/21461.webp)
Kyle Trauberman
- 24,648
- 13
- 83
- 116
2
. is for string concatenation and + is for addition.
.= would append something to a string while += will add something to something.
![](../../users/profiles/2847.webp)
John Boker
- 78,333
- 17
- 93
- 129