PHP sprintf() Function

In this chapter you will learn:

  1. Definition for PHP sprintf() Function
  2. Syntax for PHP sprintf() Function
  3. Parameter for PHP sprintf() Function
  4. Additional format for PHP printf() Function
  5. Padding the Output
  6. Specifying Number Precision
  7. Swapping Arguments
  8. Return for PHP sprintf() Function
  9. Note for PHP printf() Function
  10. Example - Replace format with value
  11. Example - A demonstration of all possible format values
  12. Example - Use of placeholders
  13. Example - A demonstration of string specifiers

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"   
//  j  av a 2s . com

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//j av a  2  s  .  c  om
$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/*from j  ava  2s .  co 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/* j a  va  2s .  c o m*/
$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   j  a v a 2 s.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.

Next chapter...

What you will learn in the next chapter:

  1. Definition for PHP sscanf() Function
  2. Syntax for PHP sscanf() Function
  3. Parameter for PHP sscanf() Function
  4. Format for PHP sscanf() Function
  5. Additional format values
  6. Return for PHP sscanf() Function
  7. Example - Parse a string
  8. Example - Using the format values %s, %d and %c
Home » PHP Tutorial » PHP String Functions
PHP addcslashes() Function
PHP addslashes() Function
PHP bin2hex() Function
PHP chop() Function
PHP chr() Function
PHP chunk_split() Function
PHP convert_cyr_string() Function
PHP convert_uudecode() Function
PHP convert_uuencode() Function
PHP count_chars() Function
PHP crc32() Function
PHP crypt() Function
PHP echo() Function
PHP get_html_translation_table() Function
PHP hebrev() Function
PHP hebrevc() Function
PHP hex2bin() Function
PHP html_entities() Function
PHP html_entity_decode() Function
PHP htmlspecialchars() Function
PHP htmlspecialchars_decode() Function
PHP join() Function
PHP lcfirst() Function
PHP levenshtein() Function
PHP localeconv() Function
PHP ltrim() Function
PHP md5() Function
PHP metaphone() Function
PHP money_format() Function
PHP nl2br() Function
PHP nl_langinfo() Function
PHP number_format() Function
PHP ord() Function
PHP parse_str() Function
PHP print() Function
PHP print_r() Function
PHP printf() Function
PHP quoted_printable_decode() Function
PHP quoted_printable_encode() Function
PHP quotemeta() Function
PHP rawurldecode() Function
PHP rawurlencode() Function
PHP rtrim() Function
PHP setlocale() Function
PHP sha1() Function
PHP similar_text() Function
PHP soundex() Function
PHP sprintf() Function
PHP sscanf() Function
PHP str_getcsv() Function
PHP str_ireplace() Function
PHP str_pad() Function
PHP str_repeat() Function
PHP str_replace() Function
PHP str_rot13() Function
PHP str_shuffle() Function
PHP str_split() Function
PHP str_word_count() Function
PHP strcasecmp() Function
PHP strchr() Function
PHP strcmp() Function
PHP strcoll() Function
PHP strcspn() Function
PHP strip_tags() Function
PHP stripcslashes() Function
PHP stripslashes() Function
PHP stristr() Function
PHP strlen() Function
PHP strnatcasecmp() Function
PHP strnatcmp() Function
PHP strncasecmp() Function
PHP strncmp() Function
PHP strpbrk() Function
PHP strpos() Function
PHP strrchr() Function
PHP strrev() Function
PHP strripos() Function
PHP strrpos() Function
PHP strspn() Function
PHP strstr() Function
PHP strtok() Function
PHP strtolower() Function
PHP strtoupper() Function
PHP strtr() Function
PHP substr() Function
PHP substr_compare() Function
PHP substr_count() Function
PHP substr_replace() Function
PHP trim() Function
PHP ucfirst() Function
PHP ucwords() Function
PHP utf8_decode() Function
PHP utf8_encode() Function
PHP vprintf() Function
PHP vsprintf() Function
PHP wordwrap() Function