Why use sprintf function in PHP?
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.
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.
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.