PHP concatenation operator is another powerful operator that helps us to provide more meaningful content to user. The symbol of concatenation operator is . (dot)
Why Concatenation Operator (.) is used?
In PHP, while performing task, we may get various datatype values such as integer value, string value. To provide user more meaningful content, we need to combine integer value, string values together. To combine different datatype together, we use concatenation operator.
When to use concatenation Operator?
If we want to combine various values into one value, then we use concatenation operator. Remember concatenation operator combines values together.
How to use concatenation operator?
The concatenation operator symbol is dot (.)
In other programming languages such as Java, C, C++ etc the concatenation operator is +
Lets add two values and print to the screen
The output of the above code: 300.
But this is not meaningful to the user or website viewer.
The more meaningful information would be “The addition value of 100 and 200 is 300”
How can we do this?
To get the mentioned output, lets break the required result into chunks.
first chunk: The addition value of (String value)
Second chunk: 100 (this is the value of $num1- integer value)
Third chunk: and (String value)
Fourth chunk: 200 (this is the value of $num2 – integer value)
Fifth chunk: is (String value)
Sixth Chunk: 300 (This is the addition result value – integer value)
After figuring out the required result in terms of chunks its time to combine them into one. To combine, we use concatenation operator.
echo “The addition of”.$num1.”and”.$num2.”is”.$num3;
In the above code, you could see various chunks are combined with . (. is concatenation operator). The output is as below.
In the above output, there is a slight problem. There is not space in between of and 100, no space between 100 and ‘and’, no space between ‘and’ and 200, no space between 200 and is, no space between is and 300.
How can we rectify this?
We need to add extra space in the string values where ever we want. Therefore the code would be as below.
echo “The addition of “.$num1.” and “.$num2.” is “.$num3;
Note: extra space added near of, extra space added at the beginning and end of ‘and’, extra space added at the beginning and end of is. See below result.
See the result is meaningful now with proper required spaces.
This way, we use concatenation operator.