How to Append and Concatenate Strings in PHP

Quick Summary

  • Use the dot operator to join two strings into a new one, and the .= operator to append text to an existing variable.
  • The dot never adds spaces between the joined parts, so put the space inside one of the strings yourself.
  • The WordPress example uses .= to append an image path to the theme folder URL from get_template_directory_uri().

PHP has two string operators. The concatenation operator (.) joins two strings into a new one, and the concatenating assignment operator (.=) appends a string to the end of an existing variable. Both work in any PHP code, including WordPress themes and plugins.

The concatenation operator

The dot returns a new string made from its left and right arguments. The original variable doesn’t change: after this code, $a is still "Hello " and $b holds "Hello World!".

PHP
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"

The space at the end of "Hello " is what separates the two words. The dot doesn’t add any spaces for you.

The concatenating assignment operator

.= appends the argument on the right to the variable on the left. $a .= "World!"; is a shorter way of writing $a = $a . "World!";.

PHP
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"

A WordPress example

.= is handy when you build a string in steps, such as a file URL. get_template_directory_uri() returns the URL of the active theme’s folder (the parent theme if you use a child theme), and the next line appends the path of an image inside it.

PHP
<?php
$i_url = get_template_directory_uri();
$i_url .=  "/assets/img/banner-dummy.jpg";
echo $i_url;
?>

echo then prints the full URL of assets/img/banner-dummy.jpg inside the theme folder. For a file that lives in a child theme, use get_stylesheet_directory_uri() instead; child and parent theme paths compares all four theme path functions. When you print the URL inside an HTML attribute, wrap it in esc_url(), one of the WordPress escaping functions.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More