PHP sprintf() Function: Format Strings & Numbers
The sprintf() function in PHP is a built-in function that returns a formatted string. The sprintf stands for string print formatted. This function allows you to format strings and numbers by inserting variable values into a formatted string.
The sprintf() function is similar to printf() function, except that the printf() function directly outputs the formatted string to the browser or concole, while the sprintf() function returns the formatted string and allows you to store it in a variable for later use. This is especially useful when you need to store the result in a variable for later use.
Syntax of sprintf() Function in PHP
The general syntax to define sprintf() function in PHP is as follows:
string sprintf(string $format, mixed ...$values);
Or,
sprintf(string $format, $value1, $value2, ...);
In the above syntax, the format string contains plain text and one or more format specifiers (placeholders), like %s, %d, %f, etc. Each specifier is replaced by a corresponding value from the list of argument values.
…$values (mixed) is a variable-length argument list of one or more values that will replace the specifiers in the format string. In other words, values will insert into the format string according to the specifiers. You can pass as many values as needed, depending on the number of format specifiers.
The sprintf() function returns a formatted string. It does not print the result like printf() function.
Basic Examples of PHP sprintf() Function
Example 1: Let’s write a PHP program in which we will format a string.
<?php
$name = "Alice";
$result = sprintf("Hello, %s!", $name);
echo $result;
?>
Output: Hello, Alice!
In this example, we have created a variable named $name and assigned a string value to it. Then, we have used the sprintf() function to format string. When the sprintf() function is called, the format specifier %s is replaced by the actual value of variable $name in the formatted string.
Since the sprintf() function returns the formatted string, we have stored it in a variable named $result. After that, we have displayed the result using echo statement on the console.
Example 2: Let’s write a PHP program in which we will format a number using sprintf() function.
<?php
$number = 12345;
$result = sprintf("The number is %d", $number);
echo $result;
?>
Output: The number is 12345
In this example, the format specifier %d is used for integers. When the sprintf() function is called, %d is replaced with the actual value of the variable named $number in the formatted string.
Example 3: Let’s write a PHP program in which we will format multiple values using sprintf() function.
<?php
$name = "Saanvi";
$age = 20;
$result = sprintf("Hello, %s. You are %d years old.", $name, $age);
echo $result;
?>
Output: Hello, Saanvi. You are 20 years old.
Types of Format Specifiers used for sprintf() Function
The sprintf() function supports several format specifiers in PHP. Some of the most commonly used format specifiers with sprintf() function are as:
- %s : String
- %d : Integer (base 10)
- %b : Integer as binary (base 2)
- %o : Integer as octal (base 10)
- %x : Integer as hexadecimal (base 16, lowercase)
- %X : Integer as hexadecimal (base 16, uppercase)
- %f : Floating point (decimal number)
- %e : Scientific notation (lowercase: e)
- %E : Scientific notation (uppercase: E)
- %c : Character with the ASCII value in the argument
- %u : Unsigned integer (base 10)
- %% : Literal percentage (%)
You can use the format specifiers to control the display of specific data types. Look at the below example.
Example 4: Floating-Point Precision
<?php
$pi = 3.14159265;
$result = sprintf("The value of PI is %.2f", $pi);
echo $result;
?>
Output: The value of PI is 3.14
In this PHP code, %.2f limits the float to 2 decimal places.
Example 5: Specifying Argument Order
<?php
$firstName = "Tripti";
$lastName = "Priya";
$message = sprintf('Welcome, %2$s %1$s!', $firstName, $lastName);
echo $message;
?>
Output: Welcome, Priya Tripti!
In this example, the %2$s replaces the second argument as a string, while the %1$s replaces the first argument as a string. You can specify the order of arguments using position specifiers.
Formatting with Type Casting
The sprintf() function in PHP automatically converts data types based on the format specifier you use. This means that even if you pass a string or a float, PHP will try to convert it to the appropriate type for the format. Let’s take some examples on it.
Example 6: Automatic Type Conversion
<?php
$value = "123.45"; // string value.
$result = sprintf("Integer value: %d", $value);
echo $result;
?>
Output: Integer value: 123
In this example, we have created a variable named $value and assigned a string containing a number with decimals “123.45”. Here, PHP automatically converts the string to an integer, dropping the decimal part (.45). Therefore, the output becomes: Integer value: 123.
Example 7:
<?php
echo sprintf("Binary: %b \n", 10);
echo sprintf("Octal: %o \n", 17);
echo sprintf("Hexadecimal: %x \n", 255);
echo sprintf("Floating-point: %f \n", 3.14);
echo sprintf("Scientific notation: %e \n", 300000);
echo sprintf("Character: %c", 65);
?>
Output: Binary: 1010 Octal: 21 Hexadecimal: ff Floating-point: 3.140000 Scientific notation: 3.000000e+5 Character: A
In this example, the sprintf() function easily converts numbers between different bases, such as binary, octal, etc.
Padding and Flags
The sprintf() function provided by PHP also supports advanced formatting using flags and padding.
Example 8:
<?php
// Padding the number with zeroes to make it 5 digits.
echo sprintf("%05d \n", 42);
// Formatting with sign.
echo sprintf("%+d \n", 42);
echo sprintf("%+d \n", -42);
// Custom formatting: * is used as padding character.
echo sprintf("%'*-10s", "PHP");
?>
Output: 00042 +42 -42 PHP*******
In this tutorial, we learned about PHP sprintf() function, which is used to format any string or number, including values of the variable. I hope that you will have understood the basic concepts of sprintf() function and practiced all examples.