• 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
  • Web Sites
  • Online Marketing
  • WordPress Support
    • Customized WordPress Training
    • 60-for-60 Sessions
  • Web Applications
  • Blog
    • Archive Listing Minimalistic
    • Blog Articles Grouped by Category
    • Case Studies
    • General
    • Portfolio
    • Reviews
    • Snippets
    • Techniques
  • Contact Jeff
    • Purchase Retainer Consulting Hours
    • About Retainer Consulting Hours

By Jeff Cohan, April 25, 2017

Why, When, and How to use sprintf and printf

Last updated May 10th, 2018 at 12:43 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 applicaiton 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.

Related Posts

  1. Diagnostic PHP: Get All Included Files
  2. Sort Multidimensional Arrays with PHP array_multisort
  3. Display WordPress and WooCommerce Tags as Lists
  4. Get From Foreigner (utility function)
  5. Biting the bullet
  • Choose the best match.

Written by Jeff Cohan · Categorized: Techniques · Tagged: php

  • Choose the best match.

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

  • Use Case for Custom Post Type: “In The News” March 10, 2023
  • Create a Custom Shortcode to Display a MemberPress Membership Price ANYWHERE on Your Website February 5, 2023
  • Avoid Direct Styling; Use CSS Instead September 21, 2022
  • Blog Tags: What They Are (and What They’re Not) August 5, 2022
  • How to Create a Simple Custom Events Plugin May 24, 2022

Filter By Category/Tag

Categories

  • Case Studies (7)
  • General (61)
  • Portfolio (5)
  • Reviews (12)
  • Snippets (16)
  • Techniques (38)

Popular Tags

Advanced Custom Fields Blogging Child Themes Content Marketing CSS CSS Grid Customer Service Custom Fields Custom Post Types Diagnostics Facebook FooGallery Genesis Gutenberg HTML Images iPhone Libra Live Chat Marketing Media MemberPress MemberPress Courses mu-plugins MySQL Photo Gallery php Pinterest Plugins Post Formats Pricing Project Management Security SEO Seth Godin Shortcodes Social Networking Surveys Taxonomies Trello Twitter Video Web design Web forms WordPress

siteground wp hosting

Web Hosting

wp101

EasyWordPresstutorialvideosforbeginners.
MemberPress CTA

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

770-772-5134
Email Jeff
Send Money
All Ways

Copyright 2023, nSiteful Web Builders, Inc.

 

Subscribe

Pardon the interruption. I know popups can be annoying. But I’d love to have you as a subscriber.

Sign up to be notified when new articles are published. Unsubscribe any time.

* indicates required

Powered by MailChimp

×