Learning PHP: Concatenate Strings and Variables Efficiently

A slightly weird term you’ll hear people use around PHP: “concatenate.” I still remember the first time I heard that word, having no earthly idea what it meant. It turns out it was a common and useful task in PHP: join two strings together so that we get a single string or something that we can echo to the screen.

Today we’ll cover all the major areas of PHP string concatenation: how to do it, why you’ll do it, what the PHP concatenation operator is, and a little of the downsides of doing PHP string concatenation too much.

Understand String Concatenation in PHP: Join Two Strings

We use “string concatenation” to put sequences of characters together in PHP

So we build a lot of HTML in PHP. And even when we aren’t doing that, we’re often processing text. For those reasons, we often want to bring together two different well, strings. (By which I mean the specific data type, a string, as opposed to integer or others.)

So we use “string concatenation” to put things together in PHP. We can use it to put a number into a string, or even more commonly we put the string together with another or other string.

The PHP concatenation operator: .

The PHP string concatenation operator is a period. ..

If you’ve programmed in other language, you may have experienced using the + (plus) symbol to put two (or more) strings together. That’s how JavaScript string concatenation works, for example. In PHP, we instead use the . (period, or decimal point) character to accomplish string concatenation. So when you put the dot, ., character better two different quoted strings, or a variable and string, or variable and variable, the result will be a single string that PHP will either be ready to output (with echo for example) or do further processing of.

From what you’re used to in English, the PHP concatenation operator being a . may look weird. But I promise once you know what’s happening you’ll get used to it and read it pretty seamlessly.

How to Concatenate Strings in PHP

Alright, time to get concrete. Here’s some code that shows off what a PHP concat looks like in practical reality. Here are three different ways we can echo the string “Hello World” in PHP:

echo "Hello World";
// output>> Hello World
$hello = 'Hello';
echo $hello.' World';
// output>> Hello World
$world = 'World';
$hello_world = $hello.' '.$world;
echo $hello_world;
// output>> Hello World

I’ll be honest, the above code is very silly. The second two examples are needlessly complicated. But we’re keeping them simple so we can get familiar with the concepts involved.

The very first line of our code sample is just an example of a very pedestrian use of echo in PHP to show a string. You’ll do this when you want to get text from “PHP land” to appear in the HTML of your pages. We know that the sequence "Hello World" is a “string” because it is bounded by double (or single) quotes.

Our next block first defines one string, simply the word Hello and then added to it the string World before it echoes them to the output. In PHP, appending string to string is super common. We do it to allow us to define part of the sequence further away from where we choose to display it. (Often much further away than it is in this example.)

Finally our last block creates two new variables: the word World and then the phrase Hello World as a single string. This last one thus gives us an example of PHP which will join strings with separator. In our case, the separator is just a space. A mistake I make a lot in PHP code is forgetting the space, but it’s an easy mistake to fix. Just add an extra string of a space (or a space to another string, if you prefer).

Combining Your PHP Powers: Append Strings AND Variables

In the above code, we saw clear examples of PHP string concatenation. But we can use PHP to combine other types of variables with strings, within limits. Those limits: we can’t do concatenation with complex data types like objects or arrays into strings without extra work.

But “simpler” PHP data types like integers and floats (generically, numbers) are a super common thing to see concatenated in PHP. That’ll look something like:

$percentage = 12.1 + 9 + 41.21;
echo 'Your final score: '.$percentage.' out of 100%.';
// output>> Your final score: 62.31  out of 100%
$integer = 1 + 17;
echo $integer.' centimeters in length';
// output>> 18 centimeters in length

In both of the examples, we’re putting the number (a float in the first case, an integer in the second) directly into the string via concatenation. Because PHP will do the “type juggling” for us to make that number into a string, we’re able to do this quickly and with ease. In PHP, adding to strings with concatenation is easy for basic types with obvious string versions.

PHP String Interpolation? Use Single or Double Quotes?

So a thing I rarely use, but is very good to understand is PHP string interpolation. What I mean (as do most people who might say it) by “string interpolation” is where you actually embed a $variable into a string in PHP, and it gets replaced immediately by the $variable‘s underlying value. So that’d look something like:

$number = 4;
echo "She has $number cars in her garage.";
// or
echo "She has {$number} cars in her garage.";
// output>> She has 4 cars in her garage

A few important things about the above. First: both echo statements will lead to the output of “She has 4 cars in her garage.” Second, we thus know that the the wrapping {} do not show. Third, it is crucial that both of the statements and strings above are using double-quotes: " and not single-quotes '. In PHP, you must match the opening and closing quote character for your strings. Further, you may when using double quotes, allow the PHP engine to interpolation the variable into it. So we could accomplish the same thing with single-quotes only if we did:

$number = 4;
echo 'She has '.$number.' cars in her garage.';
// output>> She has 4 cars in her garage

Here we’re using the PHP concatenate operator, . again, rather than relying on PHP string interpolation. There is good-and-bad in both of these options. And all three work fine. The performance overhead of using string interpolation on double-quoted strings is small enough that I don’t think you should worry about it. But you will hear people point to the (true) fact that the third example in this section is (very marginally) faster.

An Odd-Ball One: .= Is a Concatenation Assignment Compounded in PHP

Finally, you’ll see this used sometimes, and it’s very relevant to the topic. You can use the combination of a . and an = as both an assignment and a concatenation. To understand this better, let’s revisit this examples from earlier:

$hello = 'Hello';
$world = 'World';
$hello_world = $hello.' '.$world;
echo $hello_world;
// output>> Hello World

I’ve changed nothing about the above code. But you could write PHP to join two strings in quite a different way. That’s look like this:

$output = 'Hello';
$output .= ' ';
$output .= 'World';
echo $output;
// output>> Hello World

So what this does is concatenate to the end of out $output string the space (), and then then word World. So the result is that we get the same exact output. So effectively each time you see .= it is the same as $output = $output.$new_thing; or similar. Whether you like or dislike this example is a matter of personal taste. But as you read other people’s code I’m sure you’ll see people use this from time to time, so it’s good to understand this aspect of PHP concatenation.

Now Go, Concatenate Your Strings. Thoughtfully

Before I close outright, a short warning: learning the power to
“concat” strings with PHP is important and very valuable. But it’s also often a sign that you’re doing less-efficient things that you should. Templates (files that just contain your HTML + already-arranged variables) are often a better solution for most of things you’re doing than simply slamming together lots of strings of HTML sequences and variables inside of say, a WordPress functions.php file.

That said, concatenation in PHP is a fun and important thing to master. While I think it must be used sparingly, I’ll also say that in the ten-ish years I’ve been writing PHP there’s probably never been a single week where I didn’t use the powers of PHP string concatenation. Good luck!


1 Response

Comments

  • HughC says:

    It might be handy to add a bonus points / next level section on `sprintf()`, which is the function I reach for whenever I have more than basic string output to assemble. It offers more power and I adds more readability to code.

Add a Comment

Your email address will not be published. Required fields are marked *