Concatenation of two strings in PHP


PHP offers different kinds of operators having distinctive functionalities. Operators enable us to perform arithmetic activities, string concatenation, compare values and to perform boolean operations, more...In this article, we will learn string operators given by PHP. Let's first learn the types of string operators in php. There are two string operators provided by PHP. 

 1.Concatenation Operator ("."): 

     This operator combines two string values and returns it as a new string.

 2.Concatenating Assignment operator (".="): 

     This operation attaches the argument on the right side to the argument on the left side.

 Let's demonstrate the utility of the above operators by following examples.

Example:

<?php
$a = 'Good';
$b = 'Morning';
$c = $a.$b;
echo " $c ";
?>

Output :

Goodmorning

Explanation:

Here we have taken two variables $a and $b s string. Then we have used the Concatenation operator(.) to concatenate those strings into a single string.

Example:

<?php
   $a = 'Hello';
   $b = [" Good morning"," Folks"];
   for($i = count($b)-1; $i >= 0;$i--) {
$a .= $b[$i];
}
echo " $a";
?>

Output:

Hello Folks Good morning

Explanation:

In this example, we have concatenated string values with array values with the help of the Concatenating Assignment operator (".="). $a represents a string while $b represents an array, we have concatenated string $a with the values of an array $b by using a for loop.

Note:

The Concatenation Operator ('.') has a similar priority as "+" and " -" operator, which can produce unexpected results.

Example:

<?php
$val = 5;
echo "Result: " . $val + 5;
?>

Output:

5

Explanation:

The above will print out "5" rather than "Result: 10" since first the string "Result5" is created and then it is added to 5 yielding 5 because the non-empty non-numeric string "Result5 " will be converted to 0 and add with 5 to yield 5. To print "Result: 10", use parentheses to change precedence:

<?php
$var = 5;
echo "Result: " . ($var + 5);
?>

Output:

Result:10

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements