Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Concatenation of two strings in PHP program
In PHP, string concatenation is performed using the dot operator (.). This operator joins two or more strings together to create a single string.
Syntax
$result = $string1 . $string2;
Example 1: Concatenating Simple Strings
Let's start with a basic example of concatenating two string variables ?
<?php
$val1 = 'Jack';
$val2 = 'Sparrow';
echo "First Name = $val1<br>";
echo "Second Name = $val2<br>";
$res = $val1 . $val2;
echo "Concatenation = $res<br>";
?>
This will produce the following output ?
First Name = Jack Second Name = Sparrow Concatenation = JackSparrow
Example 2: Adding Spaces Between Strings
You can also concatenate strings with spaces or other characters in between ?
<?php
$firstName = 'John';
$lastName = 'Doe';
$fullName = $firstName . ' ' . $lastName;
echo "Full Name: $fullName<br>";
// Using multiple concatenations
$greeting = 'Hello, ' . $firstName . ' ' . $lastName . '!';
echo $greeting;
?>
This will produce the following output ?
Full Name: John Doe Hello, John Doe!
Example 3: Concatenating Numbers and Strings
PHP automatically converts numbers to strings during concatenation ?
<?php
$a = 1.967;
$b = 1.969;
$res = $a . " and " . $b;
echo "$res<br>";
if((round($a, 2)) == (round($b, 2))) {
echo "Both the values are equal when rounded!";
} else {
echo "Both the values aren't equal";
}
?>
This will produce the following output ?
1.967 and 1.969 Both the values are equal when rounded!
Concatenation Assignment Operator
PHP also provides the .= operator for appending strings to existing variables ?
<?php
$message = "Hello";
$message .= " World";
$message .= "!";
echo $message;
?>
This will produce the following output ?
Hello World!
Conclusion
PHP string concatenation using the dot operator (.) is simple and flexible. Use . to join strings and .= to append to existing variables. PHP automatically handles type conversion during concatenation.
