Last updated May 31st, 2023 at 03:02 pm
This article is for php coders who are familiar with the sprintf (and printf) functions but who haven’t yet figured out why, when, and how they should use them. Until recently, I was one of them. Although I’ve been coding in php since 2001, I could count on one hand the number of times I’ve used either function.
My “aha moment” was yesterday. And I want to share what I discovered, in case it helps any of you.
(Hint: It has to do with enhanced maintainability.)
What Is sprintf()
I’m going to talk about the sprintf() function, because the printf() function is essentially identical. Both generate a formatted string using some input (often a variable) and a format rule. The difference is that sprintf()
returns the string; printf()
echoes/prints the string.
You can refer to the online php manual for details on sprintf() and printf().
A typical example of the use of sprintf() comes from the PHP manual.
<?php $num = 5; $location = 'tree'; $format = 'There are %d monkeys in the %s'; echo sprintf($format, $num, $location); ?>
The result would be:
There are 5 monkeys in the tree
Ok. “But what’s the big deal?” you might ask. (I did, until recently.) Why not just do it like this, using basic php concatenation and standard variables:
<?php $num = 5; $location = 'tree'; echo "There are $num monkeys in the $location"; // or... echo 'There are ' . $num . ' monkeys in the ' . $location; ?>
Same result:
There are 5 monkeys in the tree
Some say that using sprintf() instead of basic php concatenation with variables improves readability of code. I can see that. But the readability difference never struck me as very significant.
There must be something I was missing…
My Aha Moment: A Use Case That Makes Sense
I don’t know about you, but I am so tired of online coding tutorials whose examples use “Hello, World” and “foo bar”. And the OOP tutorials that use a bicycle or car as their use cases. They don’t work for me.
What finally worked for me regarding sprintf and printf was this discussion thread in stackexchange. The key comment, by macinjosh, was this:
Essentially it allows some separation in the code. If I use ‘Hello, My Name is %s’ in many places in my code I can change it to ‘%s is my name’ in one place and it updates everywhere else automagically, without having to go to each instance and move around concatenations.
The key to sprintf() is that it’s a tool for separating content from presentation. And one of the main reasons for separating content from presentation (think about CSS and HTML) is improved maintainability.
My Use Case
It turns out I have a perfect use case in a Web application I’ve built for a membership organization. And here is a simplified version.
Let’s suppose you have a number of pages in your application that display members’ names and locations (cities and states). The data comes from a database table, pulling these columns:
last_name first_name city state
And your application captures those fields into four variables:
$last_name $first_name $city $state
Initially, your client specified that this information should be displayed as follows:
Jeff Cohan of Alpharetta, GA Jan Doe of Des Moines, IA Fran Brown of Topeka, KS
You might be inclined to use the following code to display the information everywhere (I was). Note that I’m using double-quotes to simplify.
echo "$first_name $last_name of $city, $state";
Now suppose your client says he wants this member information to be displayed like this:
Cohan, Jeff (Alpharetta, GA) Doe, Jan (Des Moines, IA) Brown, Fran (Topeka, KS)
You’d have to go into every file and change your contatenation string.
Here’s how sprintf() comes to the rescue.
Suppose, instead of using the above concatenation string, you used this sprintf() code:
<?php $format = '%1$s, %2$s (%3$s, %4$s)'; echo sprintf($format, $first_name, $last_name, $city, $state); ?>
And then you’d get:
Cohan, Jeff (Alpharetta, GA)
But wait a minute! “Wouldn’t I still have to go into every file and manually change the format rule?” you ask.
Yes, you would! Unless you put the format rule in its own function and then call it as the first argument of your sprintf() call! (You could also create and include a simple one-line file that specifies the format rule.) So here’s the new code, using the function:
In an included function file:
<?php function member_format() { $format = '%2$s, %1$s (%3$s, %4$s)'; return $format; } ?>
Wherever you need to display the member information:
<?php echo sprintf(member_format(), $first_name, $last_name, $city, $state); ?>
Note the position specifiers in the format definition; they are the n$
pieces that appear between %
and the type specifier — s, for string in every case of this example.
Now suppose your client changes his mind again. Now he wants every instance of the member information to read as follows:
Meet Jeff Cohan, who resides in the fine city of Alpharetta, GA
Just edit your function (or include file) to change the rule as follows:
function member_format() { $format = 'Meet %1$s %2$s, who resides in the fine city of %3$s, %4$s!'; return $format; }
Join the Discussion
If you have questions about this article, or if you have other use-case examples, I hope you’ll comment below.
Leave a Reply