PHP has specifically designed operators for the manipulation of text. Unlike languages that use the plus sign (+) for merging text, PHP uses a unique Dot (.) symbol. This keeps math and text handling strictly separated.
There are two primary operators used for strings in PHP:
| Operator | Name | Description |
|---|---|---|
. |
Concatenation | Joins two strings together |
.= |
Concatenation Assignment | Appends the right string to the left variable |
The dot operator joins two strings into a single string. It can be used with literal text, variables, or a mixture of both.
<?php
$txt1 = "Hello";
$txt2 = "World";
echo $txt1 . " " . $txt2; // Outputs: Hello World
?>
The .= operator is a shorthand way to update a string variable by adding more text to the end of it.
<?php
$message = "Welcome to ";
$message .= "RedoHub!";
echo $message; // Outputs: Welcome to RedoHub!
?>
+ with strings in PHP (e.g., "10" + "20"), PHP will try to convert them to numbers and do math instead of joining them. Always use . for text.
.= allows you to construct your template step-by-step, making your code significantly cleaner.