PHP String Concatenation: Dot Operator, .= and Examples

PHP uses a dot to join strings. It is simple, but the dot is easy to miss when it sits between several variables, quotes, and spaces. One missing space can quietly turn Hello Joe into HelloJoe. PHP will not complain. It considers that your design decision.

This guide explains how to concatenate strings using the dot operator and the concatenation assignment operator. It also shows when interpolation, implode(), or another formatting method produces clearer code.

Quick answer

Use the dot operator (.) to combine strings in PHP:

<?php
$firstName = 'Joe';
$lastName = 'Martin';

$fullName = $firstName . ' ' . $lastName;

echo $fullName;
?>

The output is:

Joe Martin

Use the concatenation assignment operator (.=) when you want to append text to an existing variable:

<?php
$message = 'Order';
$message .= ' confirmed';

echo $message;
?>

The PHP string operators documentation defines both operators. For simple variable substitution inside double-quoted strings, PHP string interpolation may be more readable.

Concatenate strings with the PHP dot operator

The dot operator joins its left and right operands and returns one string. The operands may be string literals, variables, function results, numbers, or expressions that PHP can convert to strings.

<?php
$greeting = 'Hello';
$name = 'Joe';

$message = $greeting . ', ' . $name . '!';

echo $message;
?>

This prints:

Hello, Joe!

Concatenation does not insert spaces automatically. Add every required space, comma, separator, or line break as part of the string:

<?php
$product = 'Wireless mouse';
$price = 25.50;

// Missing space
echo 'Product:' . $product;

// Space included in the literal
echo 'Product: ' . $product;

// Several values in one string
echo $product . ' costs £' . number_format($price, 2) . '.';
?>

The final statement outputs:

Wireless mouse costs £25.50.

Append text with the concatenation assignment operator

The concatenation assignment operator (.=) appends a value to an existing string variable. It is a shorter form of assigning the concatenated result back to the same variable.

<?php
$message = 'Your order';

$message .= ' has been packed';
$message .= ' and is ready for dispatch.';

echo $message;
?>

The output is:

Your order has been packed and is ready for dispatch.

The following two statements produce the same result:

<?php
$message = $message . ' More details';
$message .= ' More details';
?>

Use .= when a string is built gradually, such as a log message, email body, report, or block of HTML. Use the dot operator when creating a new value from a small, known set of parts.

Build a string inside a loop

The .= operator is useful when each loop iteration contributes another part of the final string.

<?php
$products = [
    'Keyboard',
    'Mouse',
    'Monitor',
];

$productList = '';

foreach ($products as $product) {
    $productList .= $product . PHP_EOL;
}

echo $productList;
?>

This produces:

Keyboard
Mouse
Monitor

PHP_EOL adds the line-ending sequence used by the current operating system. It is useful for command-line output and generated text files. For HTML output, use proper HTML elements instead of relying on newline characters.

For a closer comparison of \n, PHP_EOL, and HTML breaks, see PHP line breaks.

Concatenation or string interpolation?

PHP can place variables directly inside double-quoted strings. This is called string interpolation. Both approaches are valid, so choose the one that makes the value easiest to read.

<?php
$name = 'Maya';
$orderId = 1042;

// Concatenation
$message = 'Hello ' . $name . ', your order number is ' . $orderId . '.';

// Interpolation
$message = "Hello {$name}, your order number is {$orderId}.";
?>

Interpolation is often clearer for a sentence containing several variables. Concatenation works well when joining function results, conditional fragments, constants, or values that do not fit naturally inside one quoted string.

Curly braces make variable boundaries explicit. They are especially useful beside normal text or when accessing an array element or object property.

<?php
$user = [
    'name' => 'Maya',
];

echo "Welcome, {$user['name']}!";
?>

Single-quoted strings do not interpolate variables:

<?php
$name = 'Maya';

echo 'Hello $name';
?>

The output is the literal text Hello $name. Use concatenation or a double-quoted string when the variable value should appear.

Join array values with implode()

The dot operator joins individual expressions. When the values already exist in an array, implode() is usually the cleaner choice.

<?php
$categories = [
    'PHP',
    'JavaScript',
    'MySQL',
];

$categoryList = implode(', ', $categories);

echo $categoryList;
?>

The output is:

PHP, JavaScript, MySQL

The first argument is the separator placed between the array values. The separator may be a comma, space, slash, newline, or any other string.

<?php
$pathParts = [
    'images',
    'products',
    'keyboard.jpg',
];

$path = implode('/', $pathParts);

echo $path;
?>

Refer to the PHP implode() documentation for its accepted arguments and return value.

Do not replace ordinary concatenation with implode() when the values are unrelated expressions. Its purpose is to join array values, particularly when they share a consistent separator.

Be careful with operator precedence

The dot operator does not always group expressions in the order you may expect. This matters when concatenation appears beside arithmetic, comparison, or conditional operators.

Use parentheses to make the intended evaluation order explicit:

<?php
$quantity = 3;
$price = 12.50;

echo 'Total: £' . ($quantity * $price);
?>

The output is:

Total: £37.5

Formatting the number separately makes the result more suitable for display:

<?php
$quantity = 3;
$price = 12.50;
$total = $quantity * $price;

echo 'Total: £' . number_format($total, 2);
?>

This prints Total: £37.50.

Parentheses are also important when a conditional expression contributes part of a string:

<?php
$isActive = true;

$message = 'Account status: ' . ($isActive ? 'Active' : 'Inactive');

echo $message;
?>

Do not rely on remembering every operator precedence rule while reading a long expression. Parentheses cost two characters and can save twenty minutes of staring at output that looks almost correct.

How PHP converts concatenated values

PHP converts scalar values to strings when they are concatenated. Integers and floating-point values usually behave as expected:

<?php
$count = 5;
$rating = 4.8;

echo 'Count: ' . $count . PHP_EOL;
echo 'Rating: ' . $rating;
?>

Boolean and null values need more care:

<?php
$isEnabled = true;
$isDeleted = false;
$middleName = null;

echo 'Enabled: ' . $isEnabled . PHP_EOL;
echo 'Deleted: ' . $isDeleted . PHP_EOL;
echo 'Middle name: ' . $middleName;
?>

true becomes 1. Both false and null become an empty string. That output is rarely clear to a user, so convert these values deliberately:

<?php
$isEnabled = true;
$status = $isEnabled ? 'Yes' : 'No';

echo 'Enabled: ' . $status;
?>

Arrays cannot be meaningfully concatenated as plain strings. Doing so produces an Array to string conversion warning:

<?php
$roles = [
    'editor',
    'reviewer',
];

// Avoid this:
// echo 'Roles: ' . $roles;

echo 'Roles: ' . implode(', ', $roles);
?>

Objects can be concatenated only when their class defines a __toString() method.

<?php
final class Product
{
    public function __construct(
        private string $name
    ) {
    }

    public function __toString(): string
    {
        return $this->name;
    }
}

$product = new Product('Mechanical keyboard');

echo 'Product: ' . $product;
?>

For more detail on explicit and automatic conversions, see the PHPpot guide to PHP data type conversion.

Concatenating HTML safely

PHP can concatenate HTML markup, but dynamic values must be escaped for the context in which they are displayed. Concatenation itself does not make user input safe.

<?php
$productName = $_GET['product'] ?? '';

$safeProductName = htmlspecialchars(
    $productName,
    ENT_QUOTES | ENT_SUBSTITUTE,
    'UTF-8'
);

echo '<p>Selected product: ' . $safeProductName . '</p>';
?>

htmlspecialchars() converts characters such as <, >, quotes, and ampersands into safe HTML entities. Escape the dynamic value, not the complete HTML string, because the markup itself must remain valid HTML.

When a template contains more HTML than PHP, separating the markup from the processing code is usually easier to maintain:

<?php
$productName = $_GET['product'] ?? '';

$safeProductName = htmlspecialchars(
    $productName,
    ENT_QUOTES | ENT_SUBSTITUTE,
    'UTF-8'
);
?>

<p>Selected product: <?= $safeProductName ?></p>

This avoids building a large HTML document through a long chain of dot operators. The output is the same, but editors, syntax highlighters, and future developers can understand the template more easily.

The PHP manual documents the available flags and encoding behaviour for htmlspecialchars().

Do not concatenate untrusted values into SQL

String concatenation is valid for ordinary text, but it should not be used to place user input directly inside an SQL query.

<?php
$email = $_POST['email'] ?? '';

// Unsafe:
// $sql = "SELECT id FROM users WHERE email = '" . $email . "'";
?>

Escaping HTML does not make a value safe for SQL. Use a prepared statement and bind the value separately:

<?php
$email = $_POST['email'] ?? '';

$statement = $mysqli->prepare(
    'SELECT id FROM users WHERE email = ?'
);

$statement->bind_param('s', $email);
$statement->execute();

$result = $statement->get_result();
?>

See the PHPpot tutorial on preventing SQL injection with MySQLi prepared statements for a complete explanation.

Common PHP string concatenation mistakes

Using the plus operator instead of the dot

PHP does not use + to concatenate strings. The plus operator is for numeric addition.

<?php
$firstName = 'Maya';
$lastName = 'Patel';

// Incorrect:
// $fullName = $firstName + $lastName;

$fullName = $firstName . ' ' . $lastName;

echo $fullName;
?>

Developers moving between JavaScript and PHP make this mistake occasionally. Your fingers remember one language while your file extension is using another.

Forgetting spaces between values

The dot operator joins exactly what you provide. It does not add spaces or punctuation.

<?php
$firstName = 'Maya';
$lastName = 'Patel';

echo $firstName . $lastName;
?>

This outputs MayaPatel. Add the separator explicitly:

<?php
echo $firstName . ' ' . $lastName;
?>

Mixing quotes incorrectly

When a string contains quotes, either switch the outer quote type or escape the inner quote.

<?php
$product = 'Developer keyboard';

$message = "The product is called '{$product}'.";
$button = '<button type="button">Buy now</button>';
?>

Choose the version that is easiest to read. A string filled with backslashes is often a sign that another quoting style or a template would be clearer.

Adding a method call directly after an interpolated variable

String interpolation supports object properties, but method calls should normally be evaluated separately or concatenated.

<?php
final class Customer
{
    public function getName(): string
    {
        return 'Maya';
    }
}

$customer = new Customer();

$message = 'Hello, ' . $customer->getName() . '!';

echo $message;
?>

Assigning the result to a well-named variable can make a longer sentence easier to scan:

<?php
$customerName = $customer->getName();

$message = "Hello, {$customerName}!";
?>

Creating one very long concatenation chain

A long chain of literals, conditions, function calls, and variables quickly becomes difficult to debug.

<?php
$customerName = 'Maya';
$orderNumber = 1042;
$total = 49.90;

$formattedTotal = number_format($total, 2);

$message = 'Hello ' . $customerName
    . ', order #' . $orderNumber
    . ' has a total of £' . $formattedTotal
    . '.';
?>

Breaking the expression across lines is valid, but interpolation or sprintf() may express this sentence more clearly.

Use sprintf() for formatted strings

sprintf() is useful when a string contains several formatted values. It keeps the sentence structure in one place and separates it from the supplied data.

<?php
$customerName = 'Maya';
$orderNumber = 1042;
$total = 49.90;

$message = sprintf(
    'Hello %s, order #%d has a total of £%.2f.',
    $customerName,
    $orderNumber,
    $total
);

echo $message;
?>

The placeholders describe the expected value:

  • %s inserts a string.
  • %d inserts an integer.
  • %f inserts a floating-point value.
  • %.2f formats a floating-point value with two decimal places.

Concatenation is still the simpler choice for two or three straightforward parts. Use sprintf() when formatting rules or several values make the concatenated expression harder to understand.

Choose the clearest string-building method

PHP provides several ways to construct strings. The best choice depends on the shape of the data:

  • Use . to join a small number of separate values.
  • Use .= to append content to an existing string.
  • Use interpolation for readable sentences containing simple variables.
  • Use implode() to join values from an array with a common separator.
  • Use sprintf() when the output requires several placeholders or formatted values.
  • Use a PHP template instead of concatenating large blocks of HTML.

There is no prize for fitting an entire message into one clever expression. Prefer the version another developer can understand without counting dots and quotation marks.

PHP string concatenation FAQ

What operator concatenates strings in PHP?

PHP uses the dot operator (.) to concatenate strings.

<?php
$message = 'Hello' . ' ' . 'Maya';
?>

What does .= mean in PHP?

The .= operator appends a value to an existing string variable.

<?php
$message = 'Hello';
$message .= ' Maya';
?>

It is equivalent to:

<?php
$message = $message . ' Maya';
?>

Can PHP concatenate strings and numbers?

Yes. PHP converts an integer or floating-point value to a string during concatenation.

<?php
$orderNumber = 1042;

echo 'Order number: ' . $orderNumber;
?>

Format numbers explicitly when their display matters, especially for money, percentages, or fixed decimal places.

Should I use concatenation or interpolation?

Use whichever form makes the code clearer. Interpolation is often easier to read for sentences containing simple variables. Concatenation is useful when joining function results, constants, conditional expressions, or unrelated fragments.

Is string concatenation slow in PHP?

For normal application code, the performance difference between clear concatenation and interpolation is rarely important. Choose readable code first. Performance may matter when repeatedly building very large strings inside a heavily executed loop, but it should be measured with the real workload rather than assumed.

Can I concatenate an array in PHP?

Not directly. Concatenating an array produces an Array to string conversion warning. Use implode() when its values should be joined into one string.

<?php
$tags = [
    'PHP',
    'MySQL',
    'JavaScript',
];

echo implode(', ', $tags);
?>

Does concatenation make user input safe?

No. String concatenation only combines values. Escape data with htmlspecialchars() before placing it in HTML, and use prepared statements instead of concatenating input into SQL queries.

Conclusion

PHP string concatenation is based on two operators: . joins values, while .= appends a value to an existing string. They are suitable for most small string-building tasks.

Use interpolation when it makes a sentence easier to read, implode() for arrays, and sprintf() for structured formatting. For HTML, keep the template readable and escape every dynamic value for its output context.

Photo of Vincy, PHP developer
Written by Vincy Last updated: July 25, 2026
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Continue Learning

These related tutorials may help you continue learning.

2 Comments on "PHP String Concatenation: Dot Operator, .= and Examples"

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore topics
Need PHP help?