PHP sprintf() Function

Definition
In PHP, sprintf() builds a string from a format template and returns it.
Placeholders like %s and %d are replaced by the values you pass. Nothing is printed until you echo the result.
Syntax
Call sprintf() with the values you need. Start with this line.
$text = sprintf("%s has %d items", $name, $count);
| Call | What it does |
|---|
sprintf("%s is %d", "Tom", 30) | Returns "Tom is 30". |
sprintf("%.2f", 3.14159) | Returns "3.14". |
Common placeholders: %s string, %d integer, %f float, %x hex, %b binary, %% a literal percent sign.
Library declarations
sprintf(string $format, mixed ...$values): string
Parameters
| Parameter | Description |
|---|
| format | Required. The template with placeholders such as %s, %d, and %f. |
| values | Optional. One or more values to put into the placeholders, in order. |
Return Value
| Return Value | Description |
|---|
| string | The formatted string. |
PHP Examples
Example 1 — Fill in a Template
Use %s for text and %d for whole numbers.
<?php
$text = sprintf("%s has %d items", "Cart", 3);
echo $text, PHP_EOL;
How It Works
- Write a template.
%s and %d are placeholders. - Pass values in order.
"Cart" fills the first, 3 the second. - Get a string back. The result is stored in
$text. - Echo it. sprintf() never prints by itself.
Example 2 — Padding, Precision, and Number Bases
Add flags between the % and the letter to control the layout.
<?php
echo sprintf("%05.1f", 3.14159), PHP_EOL;
echo sprintf("%'*10s", "php"), PHP_EOL;
echo sprintf("%-8s|", "php"), PHP_EOL;
echo sprintf("%b", 5), PHP_EOL;
003.1
*******php
php |
101
How It Works
- Zero padding.
%05.1f means width 5, one decimal, padded with zeros. - Custom pad character.
'* fills the left side with stars. - Left align. The
- flag pads on the right instead. - Binary output.
%b prints 5 as 101.
Frequently Asked Questions
sprintf() formats values into a template string and returns the result. It does not print anything on its own.
sprintf(string $format, mixed ...$values): string. The first argument is the format. The rest are the values to insert.
sprintf() returns the string so you can store it. printf() prints the string right away and returns its length.
Use %.2f. For example, sprintf("%.2f", 3.14159) returns "3.14".
Write %% in the format string. For example, sprintf("%d%%", 50) returns "50%".
Next: sscanf()
sscanf() reads values out of a string using a format template.
sscanf() tutorial →About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
8 people found this page helpful