Web Analytics

PHP sprintf() Function

String Function PHP 4+

The sprintf() function returns a formatted string using placeholders.

Syntax

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

Common Format Specifiers

SpecifierDescriptionExample
%sString"Hello"
%dInteger42
%fFloat3.14
%.2fFloat (2 decimals)3.14
%05dZero-padded integer00042

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 string
  • number_format() - Format numbers with thousands
  • str_replace() - Simple replacement