The PHP string operator, also known as the concatenation operator, allows us to join two strings together. Strings need to be joined for various reasons, such as injecting a variable, or even splitting a long string so that it’s more readable in your IDE.
Let’s take a look at the following sentence (string): “I am sick and tired of creating operator tutorials.” We can echo it out or assign it to a variable. We can also split the string up using the concatenation operator and have as many strings as there are characters in it.
<?phpecho "I am sick and tired of creating operator tutorials.";
echo "I am sick and " . "tired" . " of creating operator tutorials";echo "2024 can't come soon enough. " .
"As soon as it does, I am " .
"buying a GT-R.";?>
One thing to note when you’re splitting a string: remember the spaces. Those can get lost really quickly.
<?phpecho "Hello" . "there"; // Hellothere
echo "Hello " . "there"; // Hello there?>
We can also concatenate variables to strings.
<?php$year = 2020;
$make = "Nissan";
$model = "GT-R";// Outputs: 2020 Nissan GT-R
echo $year . ' ' . $make . " " . $model;?>
The concatenation operator can be used with strings that are surrounded with both single and double quotes. The concatenation operator inside of a string is just a period (a punctuation mark). The concatenation operator can only be placed between two strings.
Strings can also be concatenated with numerical values, including floating point numbers.
<?php// Outputs: I am 32 years old
echo "I am " . 32 . " years old;// Outputs: It is $42.99
echo "It is $" . 42.99;?>
You may have seen the dot operator in other object-oriented programming languages, like Java. The dot operator in those languages allows you to access methods and attributes of an object. Most of those languages concatenate two strings using the + operator. In PHP, we use the arrow operator, ->, to access the methods and attributes of an object and we use the concatenation operator (.) to concatenate two strings.