PHP 8 reference · String Functions

PHP sprintf() Function

Return a formatted string built from a template with placeholders like %s, %d and %.2f. Format numbers, pad and align.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

sprintf(string $format, mixed ...$values): string

Parameters

ParameterDescription
format The template: %s string, %d integer, %.2f decimal, %05d zero-padded, %-10s left-aligned, %% a percent sign.
values The values for the placeholders, in order.

Return value

The formatted string.

Examples

Common placeholdersTry it yourself
<?php
echo sprintf("%s is %d years old", "Ada", 36), "\n";
echo sprintf("Total: %.2f", 19.5), "\n";
echo sprintf("Invoice #%05d", 42), "\n";

Output

Ada is 36 years old
Total: 19.50
Invoice #00042
Align columnsTry it yourself
<?php
foreach (["Tea" => 3.5, "Carrot cake" => 12.25] as $item => $price) {
    echo sprintf("%-12s%8.2f", $item, $price), "\n";
}

Output

Tea             3.50
Carrot cake    12.25
Argument numbers and other basesTry it yourself
<?php
echo sprintf('%2$s, %1$s', "Ada", "Lovelace"), "\n";
echo sprintf("%b %o %X %e", 10, 8, 255, 1234.5), "\n";

Output

Lovelace, Ada
1010 10 FF 1.234500e+3

Version history

VersionChange
PHP 4.0Added
PHP 8.0Too few arguments throws an ArgumentCountError instead of returning false.

In other languages

Was this page helpful?