String concatenation
Learn to concatenate strings with . and the common mistakes around it.
Joining with . and .=
In PHP you join two strings with the . (dot) operator. "Hello" . " World" yields "Hello World". The dot is not a plus (+); it does not add numbers, it joins strings.
To append to the same variable, the .= compound assignment is shorter. Instead of $msg = "Hi "; $msg .= "there"; you would otherwise write $msg = $msg . "there";. Both forms give the same result; .= is just shorter.
Common mistakes: . vs +
In PHP, . and + are different. "5" . "5" concatenates and gives "55"; "5" + "5" adds the numbers and gives 10. A number in quotes is a string; a number without quotes is a number.
The . converts both sides to strings and joins them. That is why "Age: " . 25 outputs "Age: 25". It turns the number into a string automatically. This is usually what you want; but typing . when you meant + can produce surprising results.
Exercise Grow a welcome message with .=
Assign "Welcome" to $msg. Then append ", Alex!" to $msg using .=. Finally print it with echo $msg;.
Show example solution
First write $msg = "Welcome"; then append with $msg .= ", Alex!"; then echo $msg;
Example solution:
<?php
$msg = "Welcome";
$msg .= ", Alex!";
echo $msg;
Test yourself
-
What is the output of echo "5" . "5";?
echo "5" . "5";- 10
- 5
- 25
- 55
Show answer
55 — Correct. The . joins strings; the two "5" strings become "55".
-
Write the compound concatenation operator
$msg = 'Hello'; $msg____ ' World'; echo $msg;Show answer
$msg = 'Hello'; $msg.= ' World'; echo $msg; -
Match each expression to its output
- '5' . '5'
- '55'
- 5 + 5
- 10
- 'a' . 'b'
- 'ab'