Combining two strings into one string is easy with both PHP and JavaScript.


$string1 = 'Hello';
$string2 = 'World!';
$string3 = $string1.' '.$string2;
echo $string3; // prints - Hello World!

In JavaScript:

string1 = 'Hello'
string2 = 'World!'
string3 = string1 + ' ' + string2
alert(string3) // prints - Hello World! in the JavaScript pop-up

Both of these examples are actually concatenating three strings – ‘Hello’, ‘ ‘, and ‘World!’. You can use variables, literals or constants.

To combine a string to itself in PHP, you can also do this:

$string1 = "Hello";
$string2 = "World!";
$string1 .= ' '.$string2;
echo $string1; //prints Hello World!

The .= operator concatenates the string after the operator to the end of the string on the left of the operator. In this example, the two strings (‘ ‘ and $string2) are concatenated to each other and then concatenated to $string1.

JavaScript can do the same thing with the += as the operator.

1 thought on “Concatenating Strings in PHP and JavaScript”

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top