17 Answers
17

sprintf has all the formatting capabilities of the original printf which means you can do much more than just inserting variable values in strings.

For instance, specify number format (hex, decimal, octal), number of decimals, padding and more. Google for printf and you'll find plenty of examples. The wikipedia article on printf should get you started.

Years ago I wrote a nice function for zero-padding numbers. Used for ages before realizing I could simply do sprintf('%03d', $num)
–
DisgruntledGoatSep 9 '09 at 16:46

2

PHP sprintf has all the formatting capabilities ... actually is missing an important one, %,8d for instance to get the rightly aligned 8 digit and commas separated integer. Using number_format is less convenient in a printf style.
–
ring0Nov 16 '10 at 6:41

1

@DisgruntledGoat Can you break down that formatting string ('%03d')? I think it would be really helpful. Thanks.
–
Mr. SmeeMar 9 '14 at 6:14

There are many use cases for sprintf but one way that I use them is by storing a string like this: 'Hello, My Name is %s' in a database or as a constant in a PHP class. That way when I want to use that string I can simply do 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.

I see where this would be very useful +1
–
jasondavisNov 6 '12 at 10:36

2

Although for translations it would probably be better to use position specifiers, to allow some extra flexibility when translating, i.e: echo sprintf(_("Here is the result: %1$s for this date %2$s"), $result, $date); That would allow a translation to modify the phrase like For the date %2$s, the result is %1$s
–
PatrikAkerstrandDec 12 '12 at 13:59

The best reason that I have found is that it allows you to place all the language strings in your language file were people can translate and order them as needed - yet you still know that no matter what format the string is in - you wish to show the users name.

For example, your site will say "Welcome back [[User]]" on the top of the page. As the programmer you don't know or care how the UI guys are going to write that - you just know that a users name is going to be shown somewhere in a message.

So you do can embed the message into your code without worring about what that message actually is.

Lang file (EN_US):

...
$lang['welcome_message'] = 'Welcome back %s';
...

Then you can support any type of message in any language by using this in your actual php code.

This method does of course have other uses, such as when printing output as HTML, etc.

Edit: For security reasons, when using a technique as above you must sanitise all input variables with mysql_real_escape_string() before using this method, to prevent MySQL insertion attacks. If you parse unsanitised input, your site and server will get hacked. (With exception to, of course, variables which have been completely constructed by your code and are guaranteed to be safe.)

Some of the typical cases are where you need more precise control over the output format. It can be tricky to for example make sure a specific value has specific amount of spaces padded to front, depending on its length, or that a number is outputted in a specific precise format.

There is a good chance that the second line is less efficient. Echo is designed as an output command, whereas sprintf is designed to do string token substitution. I'm not a PHP person, but I suspect that there are more objects involved with the echo. If it acts like Java would, it creates a new string each time something is added to the list, so you'd end up with 4 strings created.

sprintf is particularly useful when formatting strings that use numbers. For example,

$oranges = -2.34;
echo sprintf("There are %d oranges in the basket", $oranges);
Output: There are -2 oranges in the basket

Oranges is formatted as a whole number (-2), but will wrap around to positive numbers if one uses %u for unsigned values. To avoid this behaviour, I use the absolute function, abs(), to round the number towards zero as follows:

$oranges = -5.67;
echo sprintf("There are %d oranges in the basket", abs($oranges));
Output: There are 5 oranges in the basket

The end result is a statement with high readability, logical construction, clear formatting, and flexibility for addition of additional variables as required. As the number of variables increases in combination with functions that manipulate these variables, the benefits become more apparent. As a final example:

I was about to upvote your answer for its extellent first sentence ("sprintf is particularly useful when formatting strings that use numbers"), which is indeed the most important point of sprintf in PHP, but then seeing those convoluted examples creating fruits from "missing" fruits :), each repeatedly only showing %d (and abs(), which is irrelevant for the topic), instead of showing some of the plethora of number formatting options (which would be relevant), I changed my mind. But if you update the answer, I'll still have my upvote in the fridge for you. :) Thx, cheers!
–
Sz.Apr 18 '14 at 10:32

The argument is the same one for using templates. You'll want to separate your Textsleev from the actual variable values. Besides the additional powers of sprintf that we're mentioned about it's just a style thing.

A really good use case for using sprintf is outputting padded formats of numbers and also, when mixing different types in a string. It can be easier to read in many cases and makes it super simple to print different representations of the same variable, especially numerical ones.