PHP printf vs sprintf


Example

printf will output a formatted string using placeholders

sprintf will return the formatted string

$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?

It is also possible to format a number with these 2 functions. This can be used to format a decimal value used to represent money so that it always has 2 decimal digits.

$money = 25.2;
printf('%01.2f', $money);
#> 25.20

The two functions vprintf and vsprintf operate as printf and sprintf, but accept a format string and an array of values, instead of individual variables.