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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With