This article demonstrates how to concatenate strings in PHP.

1. Using Concatenation Operator

Unlike other programming languages, which use the + operator for concatenating two strings, PHP uses the . concatenation operator for string concatenation. It returns the concatenation of its right and left arguments.

Download  Run Code

 
Consider using the concatenating assignment operator (.=) to append one string to another. It appends the argument on the right side to the argument on the left side.

Download  Run Code

2. Using Variable Interpolation

The string concatenation using the . operator in PHP might result in performance overhead from constructing lots of intermediate strings along the way. For concatenating more than two strings, variable interpolation is a better choice. Using the curly braces syntax, you can interpolate a variable in a string literal. When a double-quoted string is processed by PHP, any interpolated variables will be parsed and replaced with their corresponding values.

Download  Run Code

 
It should be noted that the variable interpolation will only work in double-quoted strings. Interpolating a variable into a single-quoted string will result in the literal name of the supplied variable. For example, the following code tries to interpolate variables into a string literal enclosed in single quotes.

Download  Run Code

 
The above syntax encloses the variable name in curly braces for better visibility. However, it is also possible to interpolate variables within a string literal with double quotes without curly braces:

Download  Run Code

3. Using Heredoc syntax

Another option to concatenate strings in PHP is the Heredoc text. It behaves like a double-quoted string, without the double quotes. It has the syntax: <<< which is followed by an identifier, a newline, and the string itself. Finally, the same identifier is provided to close the quotation.

Download  Run Code

4. Using sprintf() function

If you want to apply some formatting options to the strings, you can use the sprintf() function for string concatenation. This is likely to run slower than all of the above proposed solutions. The printf() function can also be used if you want to output the result.

Download  Run Code

5. Using echo with commas

Finally, you can directly pass your strings to the echo statement, separated by commas (,). This will result in a minor speed improvement over the string concatenation operator (.), but will output the results and not assign them to a variable.

Download  Run Code

That’s all about concatenating strings in PHP.