What it is and why to use it
Concatenation is enough for a short greeting, but a report line often needs a consistent shape. sprintf() returns a formatted string, replacing placeholders with supplied values. Unlike printf(), it does not print directly, so the result can be returned from a function, stored or passed to a logger before it is displayed.
How it works
The format is a template containing ordinary text and percent-prefixed conversion specifiers. %s inserts a string, %d formats an integer, and %.2f formats a floating-point number to two decimal places. %04d requests a minimum width of four with leading zeroes. Use %% for a literal percent sign. Width is a minimum display width, not a validation rule or a limit on input length.
Common mistakes and limitations
Keep the format string under application control; pass user text as an argument rather than as the format. Formatting is not HTML escaping, SQL parameterisation or precise decimal arithmetic. Floating-point rounding and locale-sensitive conversions need separate consideration in financial or multilingual software.
Run the examples locally
Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.
The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.
These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.
Check your interpreter, lint and run one saved example
php -v
php -l example.php
php example.phpContinue learning
Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.
Syntax
$message = sprintf('%s completed %d lessons', $name, $count);Examples
Build a progress message
Reuse a predictable message structure without many concatenation operators.
<?php
declare(strict_types=1);
$name = 'John';
$done = 3;
$total = 5;
$message = sprintf('%s completed %d of %d lessons.', $name, $done, $total);
echo $message, PHP_EOL;
- The %s placeholder consumes name and the two %d placeholders consume the integer counts in order.
- sprintf returns the finished string instead of writing it immediately.
- echo is responsible for the visible line. A progress report could return the same message to a caller.
- Expected output: John completed 3 of 5 lessons.
Add padding and a literal percent sign
Format a display identifier and a percentage using different specifiers.
<?php
declare(strict_types=1);
$number = 27;
$percent = 80;
echo sprintf('Lesson %04d: %d%% complete', $number, $percent), PHP_EOL;
- %04d formats integer 27 with a minimum width of four, filling the leading positions with zeroes.
- %d inserts 80 and %% contributes one literal percent sign without consuming another argument.
- The leading zeroes are presentation only; number remains the integer 27. This is useful for consistent report labels.
- Expected output: Lesson 0027: 80% complete
Best practices
- Keep trusted templates separate from inserted data.
- Use formatting for presentation and validation for accepted values.
Runtime & versions
PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
PHP Manual