PHP sprintf() Function


The sprintf() function is used to writes a formatted string to a variable. It returns a formatted string.

Syntax
sprintf(format,arg1,arg2)
Parameters
Parameter Description
Format (Required) Specify the strings how to format the variable in it .
%% It returns a percent (%) sign.
%b The argument is presented as a binary number.
%c The parameter is treated as an integer and represented as the character with that ASCII.
%d The parameter is treated as a positive integer and represented as a decimal number.
%e Scientific notation with lowercase, e.g., 1.2e+2. The precision specifier specifies that the number of digits after the decimal point to be printed.
%E Similar to the e specifier but the scientific notation with uppercase, e.g., 1.2E+2.
%u The parameter is treated as an integer and represented as an unsigned integer.
%f Floating-point number (locale aware).
%f Floating-point number (non-locale aware).
%g It is a general format.
%G Similar to g specifier but it uses E and F.
%o Represented as an octal number.
%s The argument is treated as well as presented as a string.
%x It is represented as a hexadecimal number with lowercase letters.
%X It is represented as a hexadecimal number with lowercase letters.
arg1 (Required)The argument to be added the first %-sign in the formatted string
arg2,arg3 (optional)These arguments to be added the second%,third% etc. in the formatted string
Example
<?php
 $num = 100;
 sprintf("%d",$num);
?>

Output

100
A demonstration of all possible format values:
<?php
   $a = 83588709;
   $num2 = -83588709;
   $ch = 65; 

   echo sprintf("%%b = %b",$a)."<br>"; // Binary 
   echo sprintf("%%c = %c",$ch)."<br>"; //  ASCII 
   echo sprintf("%%d = %d",$a)."<br>"; // Signed decimal 

   echo sprintf("%%e = %e",$a)."<br>"; // lowercase
   echo sprintf("%%E = %E",$a)."<br>"; // uppercase
   echo sprintf("%%u = %u",$a)."<br>"; // Unsigned decimal (positive)
   echo sprintf("%%u = %u",$b)."<br>"; // Unsigned decimal (negative)
   echo sprintf("%%f = %f",$a)."<br>"; // Floating-point (ls aware)
   echo sprintf("%%F = %F",$a)."<br>"; // Floating-point (not aware) 
   echo sprintf("%%g = %g",$a)."<br>"; // Shorter of %e and %f
   echo sprintf("%%G = %G",$a)."<br>"; // Shorter of %E and %f
   echo sprintf("%%o = %o",$a)."<br>"; // Octal number

?>

Output

%b = 100111110110111011001100101
%c = A
%d = 83588709
%e = 8.358871e+7
%E = 8.358871E+7
%u = 83588709
%u = 0
%f = 83588709.000000
%F = 83588709.000000
%g = 8.35887e+7
%G = 8.35887E+7
%o = 476673145

Prev Next