The sprintf Function
The sprintf
function formats a string according to a specified pattern and returns the result. It accepts a format string as the first parameter, and subsequent parameters are the values for substitution. The format string uses special characters (format specifiers), which start with the %
sign and control the output formatting.
Syntax
sprintf(format, arg1, arg2, ...);
Format Specifiers
Specifier | Description |
---|---|
%s |
String |
%d |
Signed integer (decimal) |
%u |
Unsigned integer (decimal) |
%f |
Floating-point number (locale dependent) |
%F |
Floating-point number (not locale dependent) |
%c |
Character by ASCII code |
%x |
Integer in hexadecimal (lowercase) |
%X |
Integer in hexadecimal (uppercase) |
%o |
Integer in octal system |
%b |
Integer in binary system |
%e |
Scientific notation (lowercase) |
%E |
Scientific notation (uppercase) |
%g |
Short form of %e or %f |
%G |
Short form of %E or %F |
%% |
Percent sign |
Example
Formatting a string with an integer substitution:
<?php
$res = sprintf("There are %d apples", 5);
echo $res;
?>
Code execution result:
'There are 5 apples'
Example
Formatting with multiple substitutions:
<?php
$res = sprintf("%s has %d points", "John", 120);
echo $res;
?>
Code execution result:
'John has 120 points'
Example
Formatting floating-point numbers:
<?php
$res = sprintf("Price: $%.2f", 12.356);
echo $res;
?>
Code execution result:
'Price: $12.36'