Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

sprintf

Returns a string built from a format template.

Available since: PHP 4

Syntax

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

Parameters

ParameterTypeDescription
$formatstringA template with placeholders: `%s` for a string, `%d` for an integer, `%f` for a float.
...$valuesmixedThe values substituted for the placeholders, in order.

Return value

stringThe formatted string.

Examples

Substituting a string and a number:

<?php
 
echo sprintf('%s is %d years old', 'Anna', 25);

Output:

Anna is 25 years old

Decimal places and zero padding:

<?php
 
echo sprintf('%.2f', 3.14159), "\n";
echo sprintf('%05d', 42);

Output:

3.14
00042

Notes

The function returns the string without printing it. To print the result straight away, use printf() with the same arguments.

See also

  • implode — Joins array elements into a string.

Related recipes

In the tutorial

  • Strings — Working with strings in PHP — quotes, concatenation, length, searching, replacing and multibyte functions.

Thanks for reading!

Donate to the site — we work hard for you.