Using sprintf with multiple iterations

Photo by Jonathan Chng on Unsplash.

PHP's built-in sprintf() function is great for formatting complicated output and improving code readability. I recently had the need to output a string multiple times with some changes each time.

Basic output

To start, here's a basic usage of sprintf(). It prints a "Clear Date" hyperlink that uses jQuery to blank the field with an ID of "date".

$clearLink = <<<'NOWDOC'
<a onclick="%1$s('%2$s').val('')">%3$s</a>
echo sprintf($clearLink, '$j', //1
                         '#date', //2
                         'Clear Date'); //3

I highly recommend using the n$ position specifier syntax along with comments to number your sprintf() arguments. This makes it easier to change your format string, reuse arguments, and trace arguments to their placeholders.

This example is overly-simplified and the sprintf() is excessive, but it demonstrates the concept.

Advanced output with iterations

Now imagine that we need to print several clear links for various form inputs. Some of the sprintf() arguments will change but some will not. We can organize our output with multiple passes through sprintf().

$clearLink = <<<'NOWDOC'
<a onclick="%3$s('%1$s').val('')">%2$s</a>
// Fill placeholders that will not vary; preserve the rest
$clearLink = sprintf($clearLink, '%1$s', '%2$s',
                     '$j'); //3
// Fill the remaining placeholders
echo sprintf($clearLink, '#date', //1
                         'Clear Date'); //2
echo sprintf($clearLink, '#time', //1
                         'Clear Time'); //2
echo sprintf($clearLink, '#name', //1
                         'Clear Name'); //2

Notice that I've renumbered the placeholders in the original string. The placeholders that will vary on each iteration are numbered first. This avoids any renumbering on the first call to sprintf().

Of course this technique is not guaranteed to produce cleaner code. The added complexity may just obfuscate your logic. But keep it in your toolbox as an option for reusing complex templates.

Published under  on .



Hi! I'm Drew, the Wimpy Programmer. I'm a software developer and formerly a Windows server administrator. I use this blog to share my mistakes and ideas.