PHP String Concatenation Operator: What It Is and How to Use It
.. It joins two or more strings together into one continuous string by placing a dot between them.How It Works
Think of the string concatenation operator . in PHP as a glue that sticks pieces of text together. When you have two separate words or sentences, using . between them combines them into one longer string.
For example, if you have the word "Hello" and the word "World", using the concatenation operator will join them into "HelloWorld". You can also add spaces or punctuation by including them as strings to make the combined text look natural, like "Hello World".
This operator works by taking the string on the left and the string on the right and merging them without changing either original string.
Example
This example shows how to join two strings with a space between them using the concatenation operator ..
<?php $firstName = "John"; $lastName = "Doe"; $fullName = $firstName . " " . $lastName; echo $fullName; ?>
When to Use
Use the string concatenation operator in PHP whenever you need to combine text pieces. This is common when creating messages, building HTML output, or joining user input with other strings.
For example, you might want to greet a user by combining "Hello, " with their name, or build a full address by joining street, city, and country strings.
It helps keep your code clean and readable by clearly showing how strings are joined.
Key Points
- The concatenation operator in PHP is a single dot
.. - It joins two or more strings into one string.
- You can concatenate variables and string literals together.
- Use it to build dynamic text or messages in your programs.
Key Takeaways
. that joins strings.. to combine variables and text into one string.