PHP Tutorial - PHP sprintf() Function






Definition

The sprintf() function writes a formatted string to a variable.

It is identical to printf(). The only difference is that rather than outputing the formatted message like printf(), it saves the output to a string.

Syntax

PHP sprintf() Function has the following format.

string sprintf ( string format [, mixed argument [, mixed ...]] )

Parameter

This function takes a variable number of parameters: the first parameter is a format string, followed by zero or other parameters of various types.

The format strings for sprintf() is listed as follows.

FormatMeaning
%% A literal percent character; no matching parameter is required
%b Parameter is an integer; output it as binary
%c Parameter is an integer; output it as a character with that ASCII value
%d Parameter is a positive integer; output it as decimal
%e Scientific notation using a lowercase (e.g. 1.2e+2)
%E Scientific notation using a uppercase (e.g. 1.2E+2)
%f Parameter is a float; express it as a float
%F Floating-point number (not local settings aware)
%g shorter of %e and %f
%G shorter of %E and %f
%o Parameter is an integer; output it as octal
%s Parameter is a string; output it as a string
%uUnsigned decimal number (equal to or greather than zero)
%x Parameter is an integer; output it as hexadecimal with lowercase letters
%X Parameter is an integer; output it as hexadecimal with uppercase letters




Additional format

Additional format values are placed between the % and the letter (example %.2f):

Additional formatMeaning
+Forces both + and - in front of numbers. By default, only negative numbers are marked
'What to use as padding. Default is space. Must be used together with the width specifier. Example: %'q20s (this uses "q" as padding)
-Left-justifies the variable value
[0-9]Minimum width held of to the variable value
.[0-9]Number of decimal digits or maximum string length

The multiple additional format values must be in the same order as above.





Padding the Output

You can add characters to the left (by default) or the right of the formatted argument to pad it to a fixed width.

This is useful for adding leading zeros to a number, or horizontally align many strings by padding with spaces.

To add padding you insert a padding specifier into conversion specification, before the type specifier.

The padding specifier consists of either a zero to pad with zeros or a space character to pad with spaces, followed by the number of characters to pad the result out to. printf() then adds as many zeros or spaces as required to make the result the correct width.

For example, the following code displays various numbers, using leading zeros where necessary to ensure the result is always six digits long:

sprintf( "%06d \n", 123 );   // Displays "000123" 
sprintf( "%06d \n", 4567 );   // Displays "004567" 
sprintf( "%06d \n", 123456 );   // Displays "123456"       

The padding specifier can add characters where required, but it never truncates the output. So printf ("%06d", 12345678 ) displays "12345678" , not "345678".

This example pads various strings using leading spaces to ensure that they're right - aligned:

sprintf( "% 15s\n", "Hi" ); 
sprintf( "% 15s\n", "Hello" ); 
sprintf( "% 15s\n", "Hello, world!" ); 

You can also leave out the zero or space and just specify a number, in which case printf() pads with spaces.

You're not limited to zeros and spaces. To use your own padding character, insert an apostrophe (') followed by the character instead of the zero or space:

sprintf( "%'#8s", "Hi" ); // Displays "######Hi"   

If you want to add padding to the right rather than the left - so that the result is left-aligned rather than right-aligned, add a minus (-) symbol between the padding character and the width specifier:

sprintf( "%'#-8s", "Hi" ); // Displays "Hi######"       

Padding behaves differently when using f or F to display a float.

Specifying Number Precision

When displaying floating - point numbers with the f or F type specifier, you can use a precision specifier to indicate how many decimal places to round the number to. To add a precision specifier, insert a period (.), followed by the number of decimal places to use, before the type specifier:

sprintf( "%f \n ", 123.4567 );      // Displays "123.456700" (default precision) 
sprintf( "%.2f \n ", 123.4567 );  // Displays "123.46" 
sprintf( "%.0f \n ", 123.4567 );  // Displays "123" 
sprintf( "%.10f \n ", 123.4567 ); // Displays "123.4567000000"   

You can use a padding specifier with a precision specifier, in which case the entire number is padded to the required length including the digits after the decimal point, as well as the decimal point itself:

sprintf( "%.2f \n ", 123.4567 );    // Displays "123.46" 
sprintf( "%012.2f \n ", 123.4567 ); // Displays "000000123.46" 
sprintf( "%12.4f \n ", 123.4567 );  // Displays "    123.4567" 

If you use a precision specifier when formatting a string, printf() truncates the string to that many characters:

sprintf( "%.8s\n", "Hello, world!" );    // Displays "Hello, w"    

Swapping Arguments

The order of the additional arguments passed to printf() must match the order of the conversion specifications within the format string.

Argument swapping can change the order of the conversion specifications without being able to change the order of the arguments.

We can specify which argument you want each conversion specification to refer to. After each percentage ( % ) symbol, add the position of the argument you want to refer to (1 is the first argument after the format string, 2 is the second, and so on) followed by a dollar ($) symbol.

Your value %2$s contains %3$d and %1$d.

Return

PHP sprintf() Function returns the formatted string.

Note

Related functions: printf(), vprintf(), vsprintf(), fprintf() and vfprintf().

Example 1

Replace the percent (%) sign by a variable passed as an argument:


<?php
$number = 9;
$str = "java2s.com";
$txt = sprintf(" %u and %s.",$number,$str);
echo $txt;
?>

The code above generates the following result.

Example 2

A demonstration of all possible format values.


<?php// w  ww  . j a v  a  2 s .  c o m

$num1 = 123456789;
$num2 = -123456789;
$char = 50; // The ASCII Character 50 is 2

// Note: The format value "%%" returns a percent sign
echo sprintf("%%b = %b",$num1)."\n"; // Binary number
echo sprintf("%%c = %c",$char)."\n"; // The ASCII Character
echo sprintf("%%d = %d",$num1)."\n"; // Signed decimal number
echo sprintf("%%d = %d",$num2)."\n"; // Signed decimal number
echo sprintf("%%e = %e",$num1)."\n"; // Scientific notation (lowercase)
echo sprintf("%%E = %E",$num1)."\n"; // Scientific notation (uppercase)
echo sprintf("%%u = %u",$num1)."\n"; // Unsigned decimal number (positive)
echo sprintf("%%u = %u",$num2)."\n"; // Unsigned decimal number (negative)
echo sprintf("%%f = %f",$num1)."\n"; // Floating-point number (local settings aware)
echo sprintf("%%F = %F",$num1)."\n"; // Floating-point number (not local sett aware)
echo sprintf("%%g = %g",$num1)."\n"; // Shorter of %e and %f
echo sprintf("%%G = %G",$num1)."\n"; // Shorter of %E and %f
echo sprintf("%%o = %o",$num1)."\n"; // Octal number
echo sprintf("%%s = %s",$num1)."\n"; // String
echo sprintf("%%x = %x",$num1)."\n"; // Hexadecimal number (lowercase)
echo sprintf("%%X = %X",$num1)."\n"; // Hexadecimal number (uppercase)
echo sprintf("%%+d = %+d",$num1)."\n"; // Sign specifier (positive)
echo sprintf("%%+d = %+d",$num2)."\n"; // Sign specifier (negative)

?>

The code above generates the following result.

Example 3

Use of placeholders:


<?php
$number = 123;
$txt = sprintf("With 2 decimals: %1\$.2f \nWith no decimals: %1\$u",$number);
echo $txt;
?>

The code above generates the following result.

Example 4

A demonstration of string specifiers:


<?php//from   w ww  .  j  av a2s .  co  m
$str1 = "Hello";
$str2 = "Hello world!";

echo sprintf("[%s]",$str1)."\n";
echo sprintf("[%8s]",$str1)."\n";
echo sprintf("[%-8s]",$str1)."\n";
echo sprintf("[%08s]",$str1)."\n"; 
echo sprintf("[%'*8s]",$str1)."\n";
echo sprintf("[%8.8s]",$str2)."\n"; 
?>

The code above generates the following result.