Q:

Concatenating two strings in PHP

belongs to collection: PHP String Programs

0

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.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

How to convert array into string in PHP?... >>