PHP joins strings with the . operator. Use .= when appending to an existing string variable.
$first = 'Plus2net';
$topic = 'PHP Strings';
$message = $first . ' - ' . $topic;
echo $message;
$string1="Welcome to plus2net.com";
$string2=" PHP section ";
$string=$string1.$string2;
echo $string;
The output joins the two strings in their original order: Welcome to plus2net.com PHP section
We can add any number of strings by using " . " ( dot ) in between them. $string= " Hello, ";
$string .=" Welcome to ";
$string .=" plus2net.com ";
echo $string;
The above code will print all the strings one after other forming the complete sentence.
$string2=" PHP section ";
$string= "Welcome to plus2net.com $string2";
echo $string;
Here the code will display full string with string2 value added at the end. A function call is not evaluated inside an interpolated string. Let us try to add one function to display present date inside the welcome message. The next example intentionally shows that writing date() inside quotation marks outputs literal text rather than calling the function.
$string= "Welcome to plus2net.com $string2 today on date('m/d/y')";
We have to modify the above line like this to display current date.
$string= "Welcome to plus2net.com $string2 today on ". date("m/d/y");
echo $string;
Output is here
$str1 = "Hello";
$str2 = "World!";
echo $str1 . " " . $str2; // Output: Hello World!
$num1 = "100";
$num2 = "50";
echo $num1 . $num2; // Output: 10050
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| rajesh | 28-06-2010 |
| Good useful article. | |