HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP String Operators

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.


The String Operators

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

1. Concatenation (.)

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
?>

2. Concatenation Assignment (.=)

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!
?>
Important Distinction: If you use + 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.
Pro Tip: When building large blocks of HTML inside PHP, using .= allows you to construct your template step-by-step, making your code significantly cleaner.

Key Points to Remember

  • Use the dot (.) to merge text together.
  • The .= operator appends text to an existing variable.
  • Avoid using + for strings; it is reserved for mathematical addition.
  • You can chain multiple . operators in a single echo statement.
  • PHP is smart enough to convert numbers to strings automatically when using the dot operator.