PHP String Operators Explained with Examples
What Are PHP String Operators?
In PHP, String Operators are special symbols used to combine, manipulate, and join text data (strings).
They are essential when you want to build dynamic text outputs — like names, messages, or even HTML content.
PHP provides two main string operators:
Concatenation Operator (.)
Concatenation Assignment Operator (.=)
Let’s understand both in detail
Concatenation Operator (.)
The concatenation operator (.) is used to join two or more strings together.
It works just like the “+” symbol in math — but instead of adding numbers, it joins text.
Syntax:
$string1 . $string2Example:
<?php
$firstName = "John";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo $fullName;
?>
Output:
John Doe Explanation:
$firstName= “John”$lastName= “Doe”The
.operator combines both with a space" "in between.
Concatenation Assignment Operator (.=)
The concatenation assignment operator (.=) is used to append text to an existing string variable.
It’s a shorthand version of $str = $str . "text";.
Syntax:
$variable .= "string";Example:
<?php
$message = "Welcome";
$message .= " to PHP Programming!";
echo $message;
?>
Output:
Welcome to PHP Programming! Explanation:
The
.= operatoradds the text" to PHP Programming!"to the existing string"Welcome".
Example — Using Both Together
<?php
$greeting = "Hello";
$name = "Students";
$greeting .= ", " . $name . "!";
echo $greeting;
?>
Output:
Hello, Students!Why Use String Operators in PHP?
- To join text dynamically (e.g., names, addresses, messages).
- To generate HTML output dynamically.
- To display personalized messages to users.
- To combine user inputs or database values into readable text.
Real-Life Example: Creating a User Message
<?php
$username = "Arvinder";
$course = "PHP Basics";
echo "Hello " . $username . ", welcome to the " . $course . " course!";
?>
Output:
Hello Arvinder, welcome to the PHP Basics course!