How to Concatenate Strings in PHP: Simple Syntax and Examples
In PHP, you concatenate strings using the
. (dot) operator. Simply place the dot between two strings or string variables to join them into one combined string.Syntax
Use the . operator to join two or more strings. Each string or variable is placed on either side of the dot.
- String 1: The first string or variable.
- .: The concatenation operator.
- String 2: The second string or variable to join.
php
$string1 = "Hello"; $string2 = "World"; $combined = $string1 . " " . $string2; echo $combined;
Output
Hello World
Example
This example shows how to join two strings with a space between them using the dot operator. It prints the combined string.
php
<?php $name = "Alice"; $greeting = "Hello"; $message = $greeting . ", " . $name . "!"; echo $message; ?>
Output
Hello, Alice!
Common Pitfalls
One common mistake is using the plus sign + instead of the dot . for concatenation, which causes errors because + is for numbers in PHP.
Also, forgetting to add spaces when concatenating strings can lead to words sticking together.
php
<?php // Wrong way: // $full = "Hello" + "World"; // This does not cause a fatal error but results in 0 // Right way: $full = "Hello" . " " . "World"; echo $full;
Output
Hello World
Quick Reference
Remember these tips for string concatenation in PHP:
- Use
.to join strings. - Add spaces manually if needed.
- Do not use
+for strings. - You can concatenate multiple strings in one expression.
Key Takeaways
Use the dot operator
. to concatenate strings in PHP.Add spaces explicitly when joining strings to avoid words running together.
Never use the plus sign
+ for string concatenation in PHP.You can join multiple strings or variables in one expression using multiple dots.