Last Updated on July 7, 2021 by Roshan Parihar
In this tutorial, learn how to concatenate two string variables in PHP. The short answer is to use the PHP concatenate (.) operator to merge strings. You can join any number of strings together using the operator.
There are many other methods to join two string variables in PHP that you can find here below with examples.
Method 1: Using Concatenate (.) Operator
The concatenation operator is the simple method of merging two strings. To make spaces between the strings, you have to add space by joining it with the string using the same concatenation operator. You can check the below example to learn the method:
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare string variables $str1 = "Welcome"; $str2 = "to TutorialDeep!"; //Concatenate string variables $result = $str1." ".$str2; //Echo result echo $result; ?> |
Output
The above example contains two strings and the output shows the combined strings.
Method 2: using Implode() to Combine Strings
The implode function converts array into a string by merging the elements. You can pass the two string variables as an array to combine them using the implode()
function. The below example combines the two strings with some spaces.
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare string variables $str1 = "Welcome"; $str2 = "to TutorialDeep!"; //Combine string variables using implode() $result = implode(' ', array($str1, $str2)); //Echo result echo $result; ?> |
Output
The output in the above example shows the strings combined into a single string.
Method 3: Concatenate Two String Variables using Sprintf()
In addition to the above methods, you can also concatenate two string variables using the sprintf()
function. The function takes the argument of two strings as showing in the example below:
1 2 3 4 5 6 7 8 9 10 11 |
<?php //Declare string variables $str1 = "Welcome"; $str2 = "to TutorialDeep!"; //Join string variables using sprintf() $result = sprintf("%s %s", $str1, $str2); //Echo result echo $result; ?> |
Output
The above example shows the resulted merged strings in the output.
Out of the above methods, the best method is to use the concatenation (.) operator. It is simple and you just have to use the dot(.) and place it between the string variables to join them. You can add more string variable and use more concatenation operator among them to combine.
You May Also Like to Read