Current Location: Home> Latest Articles> PHP Concatenation Operator Explained: How to Use "." and ".=" for String Concatenation

PHP Concatenation Operator Explained: How to Use "." and ".=" for String Concatenation

gitbox 2025-06-18

1. Introduction

In PHP, the concatenation operator is used to join two strings together. The most commonly used string concatenation operator is “.”, which merges two strings into one new string.

2. Using the String Concatenation Operator

2.1 Concatenating Strings

You can join two strings using the “.” operator. This is the most basic string operation in PHP:

        
$str1 = "Hello, ";
$str2 = "world!";
echo $str1 . $str2; // Output: Hello, world!
        

2.2 Appending Strings

You can append a string to the end of another string using the “.=“ operator:


$str1 = "Hello, ";
$str1 .= "world!";
echo $str1; // Output: Hello, world!
        

3. Important Considerations for String Concatenation

3.1 Both Variables Must Be Strings

When concatenating strings, make sure both variables are of string type. If one of the variables is a number or another type, PHP will attempt to convert it to a string. If the conversion fails, a warning will be thrown.


$str1 = "Hello, ";
$str2 = 123;
echo $str1 . $str2; // Output: Hello, 123 (number is converted to string)
        

3.2 Two Strings Will Be Joined Into One

When concatenating, the two strings will be combined into one string. If you need to join multiple strings, you can use the concatenation operator multiple times.


$str1 = "Hello, ";
$str2 = "world!";
$str3 = "How ";
$str4 = "are ";
$str5 = "you?";
echo $str1 . $str2 . $str3 . $str4 . $str5; // Output: Hello, world! How are you?
        

3.3 Using Parentheses for Better Readability

Although the concatenation operator can join multiple strings, it's recommended to use parentheses to clarify the concatenation order, which improves the readability of the code:


$str1 = "Hello, ";
$str2 = "world!";
$str3 = "How ";
$str4 = "are ";
$str5 = "you?";
echo ($str1 . $str2) . ($str3 . $str4 . $str5); // Output: Hello, world! How are you?
        

Using parentheses makes the concatenation order clearer and enhances code readability.