Datadog collects and monitors your PHP app metrics and distributed traces in real-time with application performance monitoring. Decrease downtime and performance issues with Datadog APM by tracing requests across service boundaries and drilling into individual traces end-to-end with flame graphs. Start your 14-day trial for free today.

Making string concatenation readable in PHP

Original – by Freek Van der Herten – 2 minute read

Probably all PHP developers know how to concatenate strings. The most popular method is using the .-operator.  For small concatenations using this operator works fine. When lots of strings or variables need to be combined it can become cumbersome.

Here's an example:

$logMessage = 'A '.$user->type.' with e-mailaddress '.$user->email.' has performed '.$action.' on '.$subject.'.';

Wow, my fingers hurt... While typing the most time is spent on making sure the quotes are open and closed on the right places. It also isn't very readable. Especially the .'.' at the end make my eyes bleed.

A better way to create the string is to use the sprintf-function. This example produces the same string as the code above:

$logMessage = sprintf('A %s with email %s has performed %s on %s.', $user->type, $user->email, $action, $subject);

That's much better. This is much easier to type and you don't have to pay attention to opening an closing quotes. But my eyes still need to do a lot of work. To find out which string goes in which %s-placeholder you have to switch watching the beginning and end of the line of code.

There is another option to concatenate strings. It uses curly braces. Let's take a look:

$logMessage = "A {$user->type} with e-mailaddress {$user->email} has performed {$action} on {$subject}."

In my mind this is much better. This option has the least amount of characters to type. Your eyes can just read the line of code from left to right to understand what's going on. Keep in mind that this only works when using the curly braces between a double quote. The first character after the opening curly braces should be a dollar-sign.

EDIT: The curly braces syntax works well if you only need to concatenate strings. As mentioned in the comments below this post, <a href="">sprintf</a> might be a better fit when concatenating some other type of variable.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.