Concatenating Strings in PHP

To concatenate strings in PHP, you can use the concatenation operator (' . ') and the concatenate assignment operator (' .= '). The concatenation operator (' . ') returns the concatenation result of the right and left arguments. When concatenating, each subsequent line is added to the end of the previous one. A value of any type that is concatenated with a string will be implicitly converted to a string and then concatenated. The assignment operator (' .= ') adds the argument on the right side to the argument on the left side. This is a shorter way to concatenate the arguments and assign the result to the same variable. In this PHP String Concatenation example, we use the concatenation operator (' . ') and return the concatenating arguments. Click Execute to run the PHP Concatenation String Example online and see the result.
Concatenating Strings in PHP Execute
<?php
$a = 'PHP';
$b = 'string';
$c = 'concatenation';
$d = 'example';

echo $a." ".$b." ".$c." ".$d;  
?>
Updated: Viewed: 5802 times

What is PHP?

PHP, an open-source scripting language widely used for web development, can be integrated into HTML code, where PHP and HTML syntax constructs can be mixed in one file. PHP is known for its flexibility and large developer community. PHP supports multiple databases such as MySQL, PostgreSQL, and SQLite. PHP can run on many operating systems, including Windows, Linux, and macOS.

What is a string in PHP?

In PHP, a string is a sequence of characters, representing each character by a byte. Due to the limited range of a byte (256 characters), PHP strings do not support Unicode strings. However, PHP offers several ways to work with Unicode strings. You can create PHP strings using single quotes ('...'), double quotes ("..."), and Heredoc syntax (<<<). PHP provides many built-in string functions for various operations such as comparison, replacement, interpolation, splitting, etc.

PHP Concatenate Strings Examples

The following are examples of string concatenation in PHP:

Concatenating strings using concatenate operator (' . ')

To concatenate strings in PHP, you can use the concatenation operator (' . '), which will concatenate the strings and assign the result to a variable.

PHP Concatenation Operator (' . ') Example
<?php
$a = 'PHP';
$b = 'string';
$c = 'concatenation';
$d = 'example';

echo $a." ".$b." ".$c." ".$d; 
?>

#output: PHP string concatenation example

Concatenating strings using the assignment operator (' .= ')

To concatenate strings, you can aloso use the concatenation assignment operator (' .= '), which adds the argument on the right side to the argument on the left side.

PHP Concatenating Assignment Operator (' .= ') Example
<?php
$full_name = 'John ';

$full_name .= 'Carter';

echo $full_name; 
?>

#output: John Carter

See also