PHP printf() Function

In this chapter you will learn:

  1. Definition for PHP printf() Function
  2. Syntax for PHP printf() Function
  3. Parameter for PHP printf() Function
  4. Additional format for PHP printf() Function
  5. Padding the Output
  6. Specifying Number Precision
  7. Swapping Arguments
  8. Note for PHP printf() Function
  9. Return for PHP printf() Function
  10. Example - Output string with printf
  11. Example - Output more than one value with printf
  12. Example - Set value type in printf
  13. Example - Output escaped %
  14. Example - Float value rounding
  15. Example - Format two values
  16. Example - Use of placeholders
  17. Example - Specifying Signs

Definition

The printf() function outputs message with specified format.

printf() takes a string argument called a format string, usually followed by one or more additional arguments containing the string or strings to format. It then outputs the result.

The format string contains ordinary text mixed with one or more conversion specifications. Each conversion specification requires an additional argument to be passed to printf().

The resulting formatted string is then displayed. Conversion specifications always start with a percent (%) symbol.

For example,


// Displays "Pi rounded to a whole number is: 3" 
printf( "Pi rounded to a whole number is: %d", M_PI ); 

In this example, "Pi rounded to a whole number is: %d" is the format string, and the "%d" within the string is a conversion specification.

Here's another example that uses multiple conversion specifications:

 
// Displays "2 times 3 is 6." 
printf( "%d times %d is %d.", 2, 3, 2*3 );  

Syntax

PHP printf() function has the following format.

int printf ( 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 printf() 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:


printf( "%06d \n", 123 );   // Displays "000123" 
printf( "%06d \n", 4567 );   // Displays "004567" 
printf( "%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:


printf( "% 15s\n", "Hi" ); 
printf( "% 15s\n", "Hello" ); 
printf( "% 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:


printf( "%'#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:

    
printf( "%'#-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:

 
printf( "%f \n ", 123.4567 );      // Displays "123.456700" (default precision) 
printf( "%.2f \n ", 123.4567 );  // Displays "123.46" 
printf( "%.0f \n ", 123.4567 );  // Displays "123" 
printf( "%.10f \n ", 123.4567 ); // Displays "123.4567000000"  
/*from  j av a  2s.  c  o m*/

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:


printf( "%.2f \n ", 123.4567 );    // Displays "123.46" 
printf( "%012.2f \n ", 123.4567 ); // Displays "000000123.46" 
printf( "%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:

 
printf( "%.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.

Note

Related functions:

  • sprintf(),
  • vprintf(),
  • vsprintf(),
  • fprintf()
  • vfprintf()

Return

Returns the length of the outputted string

Example 1

Output string with printf


<?php//  j a  v  a  2 s  . c om
$info = "example from java2s.com"; 
printf("There were %s.", $info); 


$str1 = "Hello";
$str2 = "Hello world from java2s.com!";

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

%s means "string parameter," which means that $info will be treated as text in printf().

The code above generates the following result.

Example 2

Output more than one value with printf


<?PHP//from  j  a  v  a  2 s .co  m
$foo = "PHP";
$bar = "java2s.com";
$baz = "has";

printf(" %s %s %s %s %s %s.", $foo, $bar, $foo, $bar, $baz, $foo); 
?>

In the code above we have six %s formatters and six variables. PHP replaces each %s with parameter.

The code above generates the following result.

Example 3

If you specify %d but provide a float, PHP will ignore the decimal part of the number.


<?PHP/*from  j  av  a  2s . c o m*/
$number = 123; 
printf("123 in binary is: %b", $number); 
printf("123 in hex is: %h", $number); 
printf("123 as a string is: %s", $number); 

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

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

The code above generates the following result.

Example 4

To output % we use %%.


<?PHP
printf("%% allows you to print percent characters"); 
?>

The code above generates the following result.

Example 5

Revolving around the use of . (a period). For example:


<?PHP
$number = 123.456; 
printf("Formatted number is %.2f\n", $number); 
?>

%f is the format term meaning float, preceding the f with .2 rounds the float to two decimal places. We could have used %.1f for one decimal place, %.8f for eight decimal places, etc.

The code above generates the following result.

Example 6

Output a formatted string:


<?php//from   ja v  a  2 s . c om
$number = 9;
$str = "Beijing";
printf("There are %u million bicycles in %s.",$number,$str);
?>

The code above generates the following result.

Example 7

Use of placeholders:


<?php/*  j  av a  2  s  . c  om*/
$number = 123;
printf("With 2 decimals: %1\$.2f
\nWith no decimals: %1\$u",$number);
?>

The code above generates the following result.

Example 8

By default, printf() displays negative numbers with a minus (-) symbol in front of them, but doesn't put a plus (+) symbol in front of positive numbers.

To change printf()'s behavior so that it always displays a sign symbol, use the sign specifier , + , in front of the type specifier. Here's an example:


<?PHP//  ja v  a 2s.co  m
printf( "%d \n", 123 );   // Displays "123" 
printf( "%d \n", -123 );  // Displays "-123" 
printf( "%+d \n", 123 );  // Displays "+123" 
printf( "%+d \n", -123 ); // Displays "-123"    
?>

The code above generates the following result.

Next chapter...

What you will learn in the next chapter:

  1. Definition for PHP quoted_printable_decode() Function
  2. Syntax for PHP quoted_printable_decode() Function
  3. Parameter for PHP quoted_printable_decode() Function
  4. Return for PHP quoted_printable_decode() Function
  5. Example - Decode a quoted-printable string to an 8-bit ASCII string
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