String Data Type & Concatenation in PHP
String is one of various data types in PHP. String is nothing more than a collection of letters. From previous tutorials, we know how to assign a string value to a variable. To concatenate a raw string to the variable value, we make use of dot (.) in between them. There are 2 more ways of performing string concatenation apart from this. First one is, directly placing your variable inside a string and second one is, in-place substitution. In in-place substitution, we wrap our variable with curly braces. Example of all 3 ways of string concatenation is given below. Personally, I prefer concatenation using dot.
<?php $hello = "Hello "; //Using dot concatenation echo $hello. "World! <br />"; //Directly placing inside a string. echo "$hello World! <br />"; //Using in-place substitution. echo "{$hello}World!"; ?>
In case, you have 2 variables holding string values and you want to concatenate them, then you can do so using .= operator. Example is given below.
<?php $hello = "Hello "; $world = "World!"; $hello .= $world; echo $hello; ?>