0
0
PhpHow-ToBeginner · 3 min read

How to Use sprintf in PHP: Syntax and Examples

In PHP, sprintf formats a string by replacing placeholders with variable values and returns the formatted string. You use it by providing a format string with placeholders like %s for strings or %d for integers, followed by the values to insert.
📐

Syntax

The sprintf function takes a format string and a list of values. The format string contains placeholders that start with % and specify the type of value to insert.

  • %s: Insert a string
  • %d: Insert an integer
  • %f: Insert a floating-point number
  • %.2f: Floating-point with 2 decimal places

The function returns the formatted string without printing it.

php
string sprintf ( string $format , mixed ...$values )
💻

Example

This example shows how to format a string with a name and age using sprintf. It inserts the string and integer into the placeholders.

php
<?php
$name = "Alice";
$age = 30;
$formatted = sprintf("My name is %s and I am %d years old.", $name, $age);
echo $formatted;
?>
Output
My name is Alice and I am 30 years old.
⚠️

Common Pitfalls

Common mistakes include:

  • Using the wrong placeholder type (e.g., %d for a string).
  • Not providing enough values for the placeholders.
  • Expecting sprintf to print output instead of returning it.

Always check that your placeholders match the types of the values you pass.

php
<?php
// Wrong: using %d for a string
$name = "Bob";
$wrong = sprintf("Name: %d", $name); // This will output 0

// Correct:
$correct = sprintf("Name: %s", $name);
echo $correct;
?>
Output
Name: Bob
📊

Quick Reference

PlaceholderDescriptionExample
%sString"Hello %s"
%dInteger number"Age: %d"
%fFloating-point number"Price: %.2f"
%%Literal percent sign"Progress: 50%%"

Key Takeaways

Use sprintf to format strings by inserting variables into placeholders.
Match placeholder types (%s, %d, %f) with the variable types you provide.
sprintf returns the formatted string; it does not print it directly.
Use %.nf to control decimal places for floating-point numbers.
Always provide enough values for all placeholders in the format string.