PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Forget Concatenation; Format your strings!

Note: This article was originally published at Planet PHP on 16 September 2010.
Planet PHP

I do it, you do it, everyone does it! We all concatenate. If you're simply combining a few variables or constants together, concatenation is the way to go. After all, it is quick and easy, and who can complain about that? However, concatenation does have two serious drawbacks: any sort of string formatting must be done manually, and it is difficult to visualize the "goal" string when it is sufficiently complex.

Fortunately, the PHP core offers sprintf/printf which can greatly improve the readability of your code and even limit the amount of work you need to do to perform common formatting and type casting on your strings.

Why is String Formatting so Great?

This is a pretty silly question, I know. Let's face it, whether or not you use sprintf, you format strings all the time. You cast variables to certain types, you format float representations of currency, you put multiple values together, etc. The key here is, sprintf makes all of that incredibly easy, and it does so while making your code easier to read.

Want to do any of the things I just mentioned? Piece of cake:

$moneyA=A29.5; printf('ApproximatelyA$%d.',A$money); //Aoutputs:AApproximatelyA$29. printf('ExactlyA$%01.2f.',A$money); //Aoutputs:AExactlyA$29.50. $totalA=A1; printf("%dAitem%sAtotal.",A$total,A$totalA!=A1A?A's'A:A''); //Aoutputs:A1AitemAtotal. $total++; printf("%dAitem%sAtotal.",A$total,A$totalA!=A1A?A's'A:A''); //Aoutputs:A2AitemsAtotal.

Visualize the Goal

We'd like to avoid doing it, but as developers of dynamic applications, we are frequently forced to build complex strings on the fly. If you handle this with concatenation, you are almost assuredly creating strings that are difficult to read without careful scrutiny. Consequently, it is difficult to determine the intent of the completed string which can cause unexpected results or trigger errors. The functionality offered by sprintf allows us to visualize the template of the string that we're ultimately trying to create, so it can greatly improve readability and save you some annoying debugging time.

Consider creating a fairly simple, dynamic email link in html:

$emailA=A'dynamic@email.com'; printf(

Truncated by Planet PHP, read more at the original (another 8359 bytes)