phpstringconcatenationprintf

Why use sprintf() versus non-functional techniques such as concatenation or interpolation?


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

For example, why should I 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

  • 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.