0
0
PHPprogramming~5 mins

String concatenation operator in PHP

Choose your learning style9 modes available
Introduction

We use the string concatenation operator to join two or more pieces of text together into one longer text.

When you want to combine a first name and last name into a full name.
When you want to add a greeting before a user's name.
When you want to build a sentence from smaller parts.
When you want to add a file extension to a filename.
When you want to create a URL by joining parts.
Syntax
PHP
$fullString = $string1 . $string2;
The dot (.) is the operator that joins strings in PHP.
You can join more than two strings by using multiple dots, like $a . $b . $c.
Examples
This joins "Hello, " and "world!" into "Hello, world!".
PHP
$greeting = "Hello, " . "world!";
This joins first name, a space, and last name into a full name.
PHP
$fullName = $firstName . " " . $lastName;
This adds the extension ".jpg" to the filename "photo".
PHP
$file = "photo" . ".jpg";
Sample Program

This program joins first and last names with a space, then prints the full name and a greeting.

PHP
<?php
$firstName = "Jane";
$lastName = "Doe";
$fullName = $firstName . " " . $lastName;
echo "Full name: " . $fullName . "\n";
$greeting = "Hello, " . $fullName . "!";
echo $greeting . "\n";
?>
OutputSuccess
Important Notes

Remember to add spaces manually if you want spaces between words.

The concatenation operator (.) automatically converts numbers and other non-string values to strings.

Summary

The dot (.) joins strings together in PHP.

You can join many strings by chaining dots.

Spaces or other characters must be added explicitly if needed.