Skip to content
PHP Logo

What is the difference between printf and sprintf in terms of output in PHP?

printf() is a function in PHP that outputs a formatted string directly to the browser or console, while sprintf() is a function that returns the formatted string instead of outputting it. If you want to store the formatted string in a variable for later use or manipulation, you should use sprintf(). If you want to immediately display the formatted string, you should use printf().

php
// Using printf() to immediately output the formatted string
$number = 10;
printf("The number is: %d", $number);

// Using sprintf() to store the formatted string in a variable
$number = 10;
$formattedString = sprintf("The number is: %d", $number);
echo $formattedString;