• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

nSiteful Web Builders

Building a Better Web - One Site at a Time.

  • Home
  • About
    • Testimonials
    • Resources
    • Partner With Me
    • Frequently Asked Questions
  • Web Sites
  • Online Marketing
  • WordPress Support
    • Customized WordPress Training
    • 60-for-60 Sessions
  • Web Applications
  • Blog
    • At-A-Glance
    • Blog Articles Grouped by Category
    • Case Studies
    • General
    • Portfolio
    • Reviews
    • Snippets
    • Techniques
  • Contact
    • Purchase Retainer Consulting Hours
    • About Retainer Consulting Hours
    • Book a Meeting with Jeff
    • Tell Me About Your Web Project
    • nSiteful Newsletter Archives
    • nSiteful Rewards

By Jeff - 4/25/2017
Cats: Techniques · Tags: php

techniques

Why, When, and How to use sprintf and printf

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.

Like what you see? Share with others and join my mailing list. No long-term commitment, unsubscribe any time.

Related Posts

  1. PHP, MySQL: Get From Foreigner (utility function)
  2. PHP: Get All Included Files
  3. PHP: Get All User Functions
  4. Sort Multidimensional Arrays with PHP array_multisort
  5. PHP: Get All User Constants

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

mailchimp signup

Subscribe to get notified when new articles are published. Unsubscribe any time. No spam. I promise. Check out my newsletter archives.

social

Twitter Facebook LinkedIn

Recent Articles

  • Custom MemberPress Pricing Pages December 19, 2025
  • CSS Data Attribute Override December 11, 2025
  • MemberPress Rules Using Custom Taxonomies and Custom Roles December 10, 2025
  • WP Staging Plugin: a First Look November 21, 2025
  • How to overlap elements with HTML and CSS (Grid) only August 13, 2025

Filter By Category/Tag

Categories

  • Case Studies (8)
  • For Staff (1)
  • General (72)
  • Portfolio (7)
  • Reviews (14)
  • Snippets (23)
  • Techniques (52)

Popular Tags

Advanced Custom Fields Blogging Child Themes Content Marketing CSS Customer Service Custom Fields Custom Post Types Diagnostics Domain Names Facebook FooGallery Genesis Hosting HTML Images iPhone Libra Live Chat Marketing Media MemberPress MemberPress Courses Membership Sites Mobile-Friendly MySQL Photo Gallery php Pinterest Plugins Post Formats Pricing Project Management SEBA SEO Seth Godin Shortcodes Social Networking Surveys Taxonomies Twitter Video Web design Web forms WordPress

Footer

Background

Web Sites | WordPress Support | Web Applications.

Formally trained in liberal arts and education (I have a B.A. in Government from Harvard and studied Secondary Education at Rutgers Graduate School), I have honed my skills in the communication arts and sciences as a teacher, trainer, instructional designer, writer, photographer, calligrapher, helpdesk manager, database programmer, and multimedia developer.

(I've also been a group counselor, waiter, bartender, bicycle messenger boy, computer salesman, carpenter's helper, financial analyst, and school board president.)

Tech

Systems since 1983.
Web sites since 1994.
PHP since 2001.
WordPress since 2007.

Contact

Book Meeting
770-772-5134
Email Jeff
Send Money
All Ways

Copyright 2026, nSiteful Web Builders, Inc.

Cookies Consent
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.
  • Manage options
  • Manage services
  • Manage {vendor_count} vendors
  • Read more about these purposes
View preferences
  • {title}
  • {title}
  • {title}
https://iframe.mediadelivery.net/embed/392008/42d18bc1-2adc-4741-b733-053d08d09c32
https://vz-000c5976-3ab.b-cdn.net/42d18bc1-2adc-4741-b733-053d08d09c32/play_720p.mp4

Receive occasional emails from Jeff