How to Concatenate/add Two Strings in PHP?

Problem:

You want to concatenate two or more strings into one.

Solution:

You can any of the following two ways to add concatenate strings. One is concatenation operator and the other is concatenating assignment operator. Let’s check how these methods work-

Method 1: Using concatenation operator(.)

You can add strings using concatenation operator which is a dot operator(.). This operator concatenates both of its left side’s and right side’s strings and returns the concatenated string.

See the following example-

<?php
$string1 = "HTML = HyperText Markup Language";
$string2 = "PHP = PHP: Hypertext Preprocessor";

echo $string3 = $string1 . ' and ' .$string2;
?>

[wpdm_file id=156]

Output:
HTML = HyperText Markup Language and PHP = PHP: Hypertext Preprocessor

From the above example you see that using this method you can add as many strings as you want just placing dot operator between every two strings .

Method 2: Using concatenating assignment operator(.=)

If you want to concatenate one string to another existing string then use concatenating assignment operator(.=). It appends the string on its right side to the string to its left side. Please note that after concatenating strings, the resulting string is stored on the left side.

See the following example-

<?php
$string1 = "HTML = HyperText Markup Language ";
echo $string1 .= "PHP = PHP: Hypertext Preprocessor";
?>

[wpdm_file id=157]

Output:
HTML = HyperText Markup Language PHP = PHP: Hypertext Preprocessor