In this tutorial, you shall learn about the difference between printf() and sprint() functions in PHP, with example programs.

PHP – Difference between printf() and sprintf()

The difference between printf() and sprintf() functions in PHP is that, printf() function directly prints the formatted string to the output, whereas sprintf() returns the formatted string.

Now let us see this in an example.

Example

In the following program, we format a string using printf() function.

PHP Program

</>
Copy
<?php
$name = "apple";
$quantity = 30;

$format = "We have $name in our stock, a quantity of $quantity.";

printf($format, $name, $quantity);
?>

Output

PHP - Difference between printf() and sprintf() - Using printf() function

Now, in the following program, we use sprintf() to format the string. Since, sprintf() returns the formatted string, we store it in a variable, and then use an echo command to print the formatted string.

PHP Program

</>
Copy
<?php>
$name = "apple";
$quantity = 30;

$format = "We have $name in our stock, a quantity of $quantity.";

$resulting_string = sprintf($format, $name, $quantity);
echo $resulting_string;
?>

Output

PHP - Difference between printf() and sprintf() - Using sprintf() function

Conclusion

In this PHP Tutorial, we learned the difference between printf() and sprintf() functions.