In this article, you will learn how to use the PHP sprintf() function.
PHP sprintf() Function
The sprintf() function in PHP is used to format a string by substituting placeholders with specified values. The function takes a string as the first argument, which contains placeholders represented by
% followed by a letter that represents the type of value to be inserted (e.g.
%s for a string,
%d for an integer, etc.). The remaining arguments are the values that will be inserted into the placeholders.
The sprintf() function is useful when you need to create a string with placeholders that will be replaced with actual values at runtime. It allows you to format the string in a specific way, such as adding leading zeros to a number or specifying the number of decimal places for a floating-point value.
In addition to the basic placeholders (
%s for strings,
%d for integers, etc.), sprintf() also supports a number of advanced placeholders that give you more control over the formatting of the string.
Here are some examples of how to use advanced placeholders:
%0xd: where x is the width of the field and d is the number of decimal places. For example, %04d will format an integer as a four-digit string with leading zeros.
%.xf: where x is the number of decimal places and f is the floating-point number. For example, %.2f will format a floating-point number with two decimal places.
%c: for character, %C for unicode character
%b: for binary representation of integer
%e: for scientific notation
You can also use sprintf() to format a string that contains multiple placeholders, and you can specify the values to be inserted into each placeholder in the order that they appear in the string.
Here is an example of how to use the sprintf() function:
<?php $name = "John"; $age = 30; $result = sprintf("My name is %s and I am %d years old.", $name, $age); echo $result; ?>
This will output:
My name is John and I am 30 years old.
It’s also important to note that the sprintf() function returns the formatted string, but does not print it. If you want to print the formatted string, you will need to use
You can also use vsprintf() which is similar to sprintf() but it take an array as an argument instead of multiple arguments.