String Concatenation with .
The dot operator joins strings; .= appends in place. Know when concatenation beats interpolation and how it interacts with +.
PHP is unusual: it uses the dot . for joining strings and the plus + strictly for numbers. That separation is a gift — "3" + "4" is 7, while "3" . "4" is "34". There is never any ambiguity.
Append in place with .=
<?php
$msg = "Hello";
$msg .= ", ";
$msg .= "world!";
echo $msg; // Hello, world!Building a big string inside a loop with .= is fine and fast in PHP because strings are mutable buffers. For joining a list, though, implode() reads better and avoids a trailing-separator dance.
Example
When to use it
- Build a SQL WHERE clause by appending filter conditions with .= only when each filter is active.
- Concatenate breadcrumb segments with ' > ' as the separator for a navigation trail.
- Avoid accidental string/number coercion by using . instead of + when joining a label with a count.
More examples
Dot operator basics
The dot joins strings; + is arithmetic and silently casts non-numeric strings to 0 — a common source of bugs.
<?php
$label = 'Total items: ' . count([1, 2, 3]);
echo $label; // Total items: 3
$wrong = 'Items: ' + 5; // 5 (string cast to 0, then +5)
$right = 'Items: ' . 5; // Items: 5
echo "\n$right";Building a query with .=
.= appends to the existing string in place, keeping conditional SQL building readable.
<?php
$filters = ['status' => 'active', 'role' => 'admin'];
$sql = 'SELECT * FROM users WHERE 1=1';
foreach ($filters as $col => $val) {
$sql .= " AND $col = '$val'";
}
echo $sql;
// SELECT * FROM users WHERE 1=1 AND status = 'active' AND role = 'admin'Concatenation vs interpolation performance
Both concatenation and interpolation are fast; prefer interpolation for simple embeds and .= for conditionally built strings.
<?php
$items = range(1, 1000);
// Concatenation (common when mixing many variables)
$out = '';
foreach ($items as $i) {
$out .= "Item $i\n";
}
// For simple embedding, interpolation is equally fast:
$name = 'World';
$msg = "Hello, $name!"; // preferred for readability
Discussion