25

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Derek Adair
  • 21,846
  • 31
  • 97
  • 134

6 Answers6

34

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
  • 18,785
  • 10
  • 55
  • 73
11

The . operator is the string concatenation operator. .= will concatenate strings.

The + operator is the addition operator. += will add numeric values.

Kyle Trauberman
  • 25,414
  • 13
  • 85
  • 121
9

.= is concatenation, += is addition

Stephen Fischer
  • 2,445
  • 2
  • 23
  • 38
2

. is for string concatenation and + is for addition.

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

John Boker
  • 82,559
  • 17
  • 97
  • 130
1

.= is string concatenation.

+= is value addition.

Jerod Venema
  • 44,124
  • 5
  • 66
  • 109
0

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

js1568
  • 7,012
  • 2
  • 27
  • 47