Concatenating two strings in PHP

Given two strings. Learn, how to concatenate them in PHP?
Submitted by Abhishek Pathak, on November 02, 2017 [Last updated : March 13, 2023]

PHP - Concatenating Strings

The server side language of the web, PHP has a lot of support when it comes to string. PHP has wide range of methods and properties on string data type but as a backend developer, basic string operations should be always in the hand. String concatenation is a basic but very useful feature of a programming language and in PHP we have same concepts.

Let's take an example,

$string1 = "Hello World!";
$string2 = "My first program.";

Suppose we have two strings. string1 and $string2. They contain a string value. Now we have to concatenate them and make them a single string. We can do this in following ways.

Creating a new concatenated string

In this method, we will create a new string that will contain both the strings combined in one string. This method is useful if we don't want to edit the original strings. We use the . period sign for concatenation in PHP.

We can concatenate it as follows,

<?php
	$string1 = "Hello World!";
	$string2 = "My first program.";

	$output = $string1 . $string2;
	echo $output; //Hello World!My first program.
?>

This creates a new string that contains the both string. Note that string1 is written after string2 as we have done in the code and there is no space in between. Now we can use the output string without editing the original strings.

Appending after the original strings

We can also append one string after another using the same . operator. We have to do just,

<?php
	$string1 = "Hello World!";
	$string2 = "My first program.";

	$string1 = $string1 . $string2;
	echo $string1; //Hello World!My first program.
?>

This appends the string2 after string1, but the result is same. Notice that now the original string1 variable has changed.

So this is how we can do string concatenation in PHP. Share your thoughts in the comments below.

PHP String Programs »



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.