printf vs sprintf

suggest change

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Outputting the value of a variable:
* printf vs sprintf

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
84 Outputting the value of a variable
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR