Signup/Sign In

How to append a string in PHP?

Answer: Using concatenation assignment (.=) operator

PHP does not offer any predefined function to append the string in PHP. But we can do this using the concatenation assignment operator. This concatenation assignment operator is denoted by the dot and equal to sign (.=). With the help of the concatenation assignment operator, we can merge as many strings as we want into one string.

The assignment concatenation (.=) operator is used when we want to join the strings into a single string and assign the result to the same variable.

Example: Append PHP string

In the given example, we append the two strings into a single string using the assignment concatenation (.=) operator.

<!DOCTYPE html>  
<html> 
<head>
	<title>Append PHP string</title>
</head> 
<body>  
	<?php
		 $str = 'Welcome to';
		 $str .= ' ';
		 $str .= 'Studytonight';
		 echo $str;
	?>
</body>  
</html>  


Welcome to Studytonight

Using concatenation operator

Apart from the assignment concatenation operator, we can also happen string using the concatenation operator. In other programming languages, the concatenation operator is denoted by the addition operator, while in PHP, the concatenation operator is denoted by the dot (.).

With the help of this operator, we can join one or more strings into one when we join string using concatenation operator when we want to join string and assign the result to a third variable.

Example: Append PHP String

In the given example, we append the two strings into single one using the concatenation (.) operator.

<!DOCTYPE html>  
<html> 
<head>
	<title>Append PHP string</title>
</head> 
<body>  
	<?php
		$str1 = 'Welcome to';
		$str2 = 'Studytonight';
		$result = $str1 . ' ' .$str2;
		echo $result;
	?>
</body>  
</html>  


Welcome to Studytonight

Conclusion

In this lesson, we have learned how to append strings in PHP. So, we can append the strings in PHP either by using a concatenation operator (.) or concatenation assignment (.=) operator. The concatenation operator is used when we want to join the string and assign the result to another variable. In comparison, the concatenation assignment operator is used when we want to join the strings and assign the result to the same variable.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.