Concatenation and increment
Learn string concatenation with . and .=, and increment/decrement with ++ and --.
String concatenation: .
In PHP, you join two strings with the . operator. It behaves like + in JavaScript, but in PHP + only adds numbers.
For example, $first . " " . $last joins the first and last names with a space between them. You can chain several parts: $greeting = "Hello" . " " . $name;.
.= and increment operators
If you keep appending to a string, the .= shortcut is very useful. After $msg = "Welcome";, writing $msg .= ", " . $name; adds the new string to the end of $msg.
To increase a number by one use ++, to decrease it by one use --. The expression $count++ means the same as $count = $count + 1; you will see it often in loop counters.
Exercise Build a greeting message
Assign the string "Hello" to $greeting as the starting value, then append $name with the . operator. Finally print $greeting with echo.
Show example solution
To join the string, write $greeting = "Hello" . " " . $name;
Example solution:
<?php
$name = "Alex";
// Build the greeting
$greeting = "Hello" . " " . $name;
echo $greeting;
Test yourself
-
What is the output of echo "Hello" . " " . "World";?
echo "Hello" . " " . "World";- Hello World
- HelloWorld
- Hello. World
- error
Show answer
Hello World — Correct. The three parts join with a space in between.
-
Write the concatenation assignment
$greeting = "Hello"; $greeting ____ " World"; echo $greeting;Show answer
$greeting = "Hello"; $greeting .= " World"; echo $greeting; -
Match each operator to its meaning
- .
- Concatenate
- .=
- Concat and assign
- ++
- Increment
- --
- Decrement