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:

  1. Concatenation Operator (.)

  2. 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 . $string2

Example:

<?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 .= operator adds 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!

Read More

How to Create Database in MySQL

  • By admin
  • November 27, 2021
  • 65 views
How to Create Database in MySQL

How to create table in MySQL

  • By admin
  • November 6, 2021
  • 46 views
How to create table in MySQL

MySQL commands with examples

  • By admin
  • September 11, 2021
  • 139 views
MySQL commands with examples

MySQL use database

  • By admin
  • May 28, 2021
  • 45 views
MySQL use database

System Software

  • By admin
  • May 20, 2021
  • 66 views

Introduction to software

  • By admin
  • May 13, 2021
  • 58 views
Introduction to software