Why use sprintf function in PHP?

JasonDavis picture JasonDavis · Sep 6, 2009 · Viewed 75.7k times · Source

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?

Answer

Isak Savo picture Isak Savo · Sep 6, 2009

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.