Concatenating two strings in PHP

By Abhishek Pathak Last updated : December 26, 2023

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.

Problem statement

Given two strings, write a PHP program to concatenate the given strings.

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.

Prerequisites

The following PHP topics are used in the below-given solutions:

Concatenating two strings in PHP

To concatenate two given strings in PHP, you can use the string concatenation operator (.). Use the dot (.) between the strings or string variables to concatenate them. There can be two approaches, either you can create a new concatenated string or you can assign the result to an existing variable.

Approach 1: 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.

Example

PHP code to concatenate two strings and create a new string.

<?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.

Approach 2: Appending after the original strings

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

Example

PHP code to concatenate two strings and append in original strings.

<?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 »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.