24

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

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Derek Adair
  • 21,351
  • 31
  • 94
  • 133

6 Answers6

33

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,358
  • 10
  • 51
  • 73
11

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

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

Kyle Trauberman
  • 24,976
  • 13
  • 86
  • 117
8

.= is concatenation, += is addition

Stephen Fischer
  • 2,335
  • 2
  • 22
  • 36
2

. is for string concatenation and + is for addition.

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

John Boker
  • 80,803
  • 17
  • 95
  • 130
1

.= is string concatenation.

+= is value addition.

Jerod Venema
  • 43,279
  • 5
  • 65
  • 109
0

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

js1568
  • 6,952
  • 2
  • 25
  • 47