Difference Between printf & sprintf

Quick Summary

  • printf() and sprintf() take the same format string and values, but printf() prints the result while sprintf() returns it.
  • printf() returns only the length of the printed text, so use sprintf() to store the string, pass it on or return it.
  • In WordPress, wrap a translation function in sprintf() so translators see the whole sentence, and escape user values with esc_html() before printing.

printf() and sprintf() in PHP take the same arguments: a format string with placeholders, followed by the values to insert. The difference is what happens to the result. printf() prints it directly, while sprintf() returns it so you can place it into a variable first.

PHP
$name = 'Jeff';

// The `%s` tells PHP to expect a string
// ↓ `%s` is replaced by ↓
printf("Hello %s, How's it going?", $name);
#> Hello Jeff, How's it going?

// Instead of outputting it directly, place it into a variable ($greeting)
$greeting = sprintf("Hello %s, How's it going?", $name);
echo $greeting;
#> Hello Jeff, How's it going?

How it works

In both calls, %s is a placeholder that expects a string, and PHP replaces it with the value of $name. Both produce Hello Jeff, How's it going?; the sprintf() version just needs an echo to show it.

  • Use printf() when you only want to output the text. Its return value is the length of the printed string, not the string itself.
  • Use sprintf() when you need the text later: to store it, pass it to another function, or return it from a function or shortcode.
  • Other common placeholders are %d for integers, %f for floats and %% for a literal percent sign. With several values, numbered placeholders such as %1$s and %2$s let you use them in any order.

In WordPress you’ll often see sprintf() wrapped around a translation function, as in sprintf( __( 'Hello %s', 'textdomain' ), $name ), so translators get the whole sentence with the placeholder in place. When the value comes from a user, escape it before printing, for example with esc_html() (see when to use esc_html, esc_attr and esc_url).

See also: Difference Between StudlyCaps and camelCase in PHP.

Share on X (opens in a new tab) Share on LinkedIn (opens in a new tab) Share on Facebook (opens in a new tab)

ChatGPT (opens in a new tab) Claude (opens in a new tab) Gemini (opens in a new tab) Perplexity (opens in a new tab) Grok (opens in a new tab)

More Insights

See More