Why use sprintf function in PHP?

I am trying to learn more about the PHP function sprintf() but php.net did not help me much as I am still confused, why would you want to use it?

Take a look at my example below.

Why use this:

$output = sprintf("Here is the result: %s for this date %s", $result, $date);

When this does the same and is easier to write IMO:

$output = 'Here is the result: ' .$result. ' for this date ' .$date;

Am I missing something here?


Solution 1:

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.

Solution 2:

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:

$name = 'Josh';
// $stringFromDB = 'Hello, My Name is %s';
$greeting = sprintf($stringFromDB, $name);
// $greetting = 'Hello, My Name is Josh'

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.

Solution 3:

Another use of sprintf is in localized applications as the arguments to sprintf don't have to be in the order they appear in the format string.

Example:

$color = 'blue';
$item = 'pen';

sprintf('I have a %s %s', $color, $item);

But a language like French orders the words differently:

$color = 'bleu';
$item = 'stylo';

sprintf('J\'ai un %2$s %1$s', $color, $item);

(Yes, my French sucks: I learned German in school!)

In reality, you'd use gettext to store the localized strings but you get the idea.


Solution 4:

It's easier to translate.

echo _('Here is the result: ') . $result . _(' for this date ') . $date;

Translation (gettext) strings are now:

  • Here is the result:
  • for this date

When translated to some other language it might be impossible or it results to very weird sentences.

Now if you have

echo sprintf(_("Here is the result: %s for this date %s"), $result, $date);

Translation (gettext) strings is now:

  • Here is the result: %s for this date %s

Which makes much more sense and it's far more flexible to translate to other languages