PHP sprintf() Function
The sprintf() function returns a formatted string using placeholders.
Syntax
sprintf(string $format, mixed ...$values): string
Common Format Specifiers
| Specifier | Description | Example |
|---|---|---|
%s | String | "Hello" |
%d | Integer | 42 |
%f | Float | 3.14 |
%.2f | Float (2 decimals) | 3.14 |
%05d | Zero-padded integer | 00042 |
Try It Online
Output
Click Run to execute your code
More Examples
Currency Formatting
<?php
$price = 19.9;
echo sprintf("Price: $%.2f", $price);
// "Price: $19.90"
?>
Zero Padding
<?php
$num = 42;
echo sprintf("%05d", $num); // "00042"
echo sprintf("%08d", $num); // "00000042"
?>
Multiple Values
<?php
$name = "John";
$age = 25;
echo sprintf("%s is %d years old", $name, $age);
// "John is 25 years old"
?>
Tip: Use
printf() to output directly instead of returning the string.
Common Use Cases
- Formatting prices and currency
- Creating padded IDs (e.g., INV-00001)
- Building log messages
- Generating formatted reports
Related Functions
printf()- Output formatted stringnumber_format()- Format numbers with thousands- str_replace() - Simple replacement
Enjoying these tutorials?