Oh Dear! monitors your entire website, not just the homepage. You'll get a notification as soon as your website is down, a monthly uptime report, a warning a few days before your SSL certificate expires and much more! Start your free 10 day trial now!

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="http://php.net/manual/en/function.sprintf.php">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.

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.