String Concatenation
Joining strings together is called concatenation, and in PHP the operator for it is a single dot: .
Example
The dot glues $x and $y into one new string:
Prompt
Write a PHP script that creates two variables with "Hello" and "World", concatenates them using the dot operator, and prints the result.
Output: PHP script
index.php
<?php
$x = "Hello";
$y = "World";
$z = $x . $y;
echo $z;
?>
Example
The words in the previous output ran together as HelloWorld, because the dot adds nothing between them. To separate them, concatenate a string holding one space in the middle:
Prompt
Write a PHP script that creates two variables with "Hello" and "World", concatenates them with a space in between using the dot operator, and prints the result.
Output: PHP script
index.php
<?php
$x = "Hello";
$y = "World";
$z = $x . " " . $y;
echo $z;
?>
Example
Double quotes offer a simpler route. Write both variables inside one double-quoted string with a space between them, and PHP keeps that space in the output:
Prompt
Write a PHP script that creates two variables with "Hello" and "World", combines them inside double quotes with a space between them, and prints the result.
Output: PHP script
index.php
<?php
$x = "Hello";
$y = "World";
$z = "$x $y";
echo $z;
?>