How to combine two strings in PHP

How to combine two strings in PHP

Sometimes we need to combine two or more strings in the project. PHP provides 2 ways to combine or join two strings together. Joining the string is very common in any programming, sometimes we need to join suffix or prefix on the string as per requirement and sometimes for making the result user friendly.

In this post, we are going to discuss two ways to combine the string. The first is a concatenation operator (‘.‘) which returns the string after combining its left and right arguments.

The second is the concatenating assignment operator (‘.=‘), which combines or appends the right side arguments to the left side arguments.

Let’s discuss first the concatenation operator (‘.‘)

Example 1

<?php
$str1 = 'Atcodex';
$str2 = 'com';
$new_str = $str1 . ' ' . $str2;
echo $new_str; 
?>

Output

Atcodex com

You can see we defined two string $str1 ans $str2 with value. With the help of concatenation operator (‘.‘) we have combined the two string into one and you can check the output.

Let’s see the second example in which we are using concatenating assignment operator (‘.=‘) to combine the string value.

Example 2

<?php 
$a = 'Atcodex'; 

$a .= "com"; 

echo " $a \n"; 
?> 

Output

Atcodexcom

You can see we defined string $a two times with value. With the help of concatenating assignment operator (‘.=‘) we have stored or combined both values into one.

Conclusion:

Combining two strings in PHP is very easy and we have explained the two possible ways, how to combine two strings in PHP. There are multiple functions in the PHP and using them we can easily handle this type of small problem in the project.

You can also check How to merge arrays in PHP? PHP merge is very common requirement and easy to use in the PHP.

Hope you guys liked the post. Please us know you have any queries and suggestion related to the post, that would be great to us to improve the post.

Spread the love

Leave a Reply

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