21

What are the differences between .= and += in PHP?

Peter Mortensen
  • 28,342
  • 21
  • 95
  • 123
Derek Adair
  • 20,298
  • 31
  • 92
  • 133

6 Answers6

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".

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.

Kyle Trauberman
  • 24,648
  • 13
  • 83
  • 116
8

.= is concatenation, += is addition

Stephen Fischer
  • 2,177
  • 2
  • 21
  • 36
2

. is for string concatenation and + is for addition.

.= would append something to a string while += will add something to something.

John Boker
  • 78,333
  • 17
  • 93
  • 129
1

.= is string concatenation.

+= is value addition.

jvenema
  • 42,243
  • 5
  • 64
  • 107
0

The main difference .= is string concatenation while += is value addition.

js1568
  • 6,800
  • 2
  • 23
  • 46