Current Location: Home> Latest Articles> Detailed explanation of the basic usage of the sprintf function in PHP

Detailed explanation of the basic usage of the sprintf function in PHP

gitbox 2025-04-28

sprintf() is a very practical string formatting function in PHP. It can insert variables into format templates and format them in a specified way. Whether it is processing numerical values, decimal alignment, or generating structured text output, sprintf() comes in handy.

This article will take you to quickly master the basic usage, formatting parameters and some practical skills of sprintf() .

1. What is sprintf()?

sprintf() is a string formatting function of PHP. Its basic syntax is as follows:

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

It formats the following values ​​based on the placeholder in the $format string and returns a formatted string (no direct output).

Let's give a simple example:

 $name = "Alice";
$age = 30;
echo sprintf("My name is %s,I'm this year %d age。", $name, $age);

Output:

 My name is Alice,I'm this year 30 age。

2. Common formatting symbols

sprintf() uses a format controller similar to C language. Here are some commonly used format symbols:

Format characters meaning
%s String
%d Signed decimal integers
%u Unsigned decimal integers
%f Floating point number
%x Hexadecimal (lowercase)
%X Hexadecimal (caps)
%o Octal
%% Output a percent sign

3. Common usage examples

1. Numerical filling and alignment

 echo sprintf("serial number:%04d", 42); // Output serial number:0042

Note: %04d means that there are 4 digits in total, and the shortage is added to the first 0.

2. Floating point accuracy control

 $price = 123.456;
echo sprintf("price:%.2f Yuan", $price); // Output price:123.46 Yuan

Description: .2 means that two decimal places will be retained and will be rounded.

3. Dynamically construct URLs

 $userId = 987;
$token = 'abc123';

$url = sprintf("https://gitbox.net/user/%d/profile?token=%s", $userId, $token);
echo $url;

Output:

 https://gitbox.net/user/987/profile?token=abc123

4. Advanced skills

1. Parameter reuse and numbering

 echo sprintf("On the other hand:%2\$s yes %1\$s", "teacher", "student");
// Output:On the other hand:student yes teacher

Description: %2\$s means using the second parameter, and %1\$s means using the first parameter.

2. Compare with printf()

sprintf() returns a string, while printf() is the direct output. The syntax of the two is almost the same:

 $message = sprintf("Hello, %s!", "World");
echo $message;

// Equivalent to
printf("Hello, %s!", "World");

5. Common scenario applications

1. Log formatting

 $level = "ERROR";
$message = "Unable to connect to the database";
$log = sprintf("[%s] %s", $level, $message);
echo $log;
// Output:[ERROR] Unable to connect to the database

2. Table style output (alignment)

 printf("%-10s | %5s\n", "product", "price");
printf("%-10s | %5.2f\n", "apple", 3.5);
printf("%-10s | %5.2f\n", "banana", 2.2);

Output:

 product        | price
apple        |  3.50
banana        |  2.20

Description: %-10s means left alignment, accounting for 10 characters.

6. Things to note

  • Don't forget the format character after % , as missed writing will throw an error.

  • When multiple formatting parameters are formatted, the order must match the order in format unless the number is used.

  • You can nest sprintf() to generate more complex output content.

7. Summary

sprintf() is a powerful and flexible string formatting tool, mastering it allows you to write cleaner and maintainable PHP code. Whether it is processing text output, structuring URLs, or formatting data display, sprintf() is an indispensable tool for you.

Use it in the project now!