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.
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!
You can append a string to the end of another string using the “.=“ operator:
$str1 = "Hello, ";
$str1 .= "world!";
echo $str1; // Output: Hello, world!
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)
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?
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.