Categories: PHP

printf – PHP String Functions

Syntax :

printf ( string_format, arg1, arg2, arg3… );

Description :

The printf() function output a formatted string. Output will come according to the string_format. The arg1, arg2, ++ parameters will be inserted at percent (%) signs in the main string.

This function works “step-by-step”.

  • At the first % sign, arg1 is inserted,
  • at the second % sign, arg2 is inserted, etc.

Note: If there are more % signs than arguments, you must use placeholders. A placeholder is inserted after the % sign, and consists of the argument- number and “\$”. See example one.


Parameter :

[table caption=”” width=”100%” colwidth=”15%|15%|15%|55%” colalign=”left|lef|lef|left”]
Name, Required /Optional, Value Type, Description
string_format, Required, String , Specifies the string and how to format the variables in it.
arg1, Required, Mixed , Required. The argument to be inserted at the first %-sign in the format string
arg2, Optional, Mixed , Optional. The argument to be inserted at the second %-sign in the format string
arg3, Optional, Mixed , The argument to be inserted at the third and fourth and so on etc. %-sign in the format string.
[/table]


Output :

It will returns the length of the outputted string.


Description :

string_format, Required, String , Specifies the string and how to format the variables in it.

The format string is composed of zero or more directives: ordinary characters (excluding %) that are copied directly to the result and conversion specifications, each of which results in fetching its own parameter. This applies to both sprintf() and printf().

Each conversion specification consists of a percent sign (%), followed by one or more of these elements, in order:

  1. An optional sign specifier that forces a sign (- or +) to be used on a number. By default, only the – sign is used on a number if it’s negative. This specifier forces positive numbers to have the + sign attached as well.
  2. An optional padding specifier that says what character will be used for padding the results to the right string size. This may be a space character or a 0 (zero character). The default is to pad with spaces. An alternate padding character can be specified by prefixing it with a single quote (). See the examples below.
  3. An optional alignment specifier that says if the result should be left-justified or right-justified. The default is right-justified; a character here will make it left-justified.
  4. An optional number, a width specifier that says how many characters (minimum) this conversion should result in.
  5. An optional precision specifier in the form of a period (.) followed by an optional decimal digit string that says how many decimal digits should be displayed for floating-point numbers. When using this specifier on a string, it acts as a cutoff point, setting a maximum character limit to the string. Additionally, the character to use when padding a number may optionally be specified between the period and the digit.
  6. type specifier that says what type the argument data should be treated as. Possible types:

    • % – a literal percent character. No argument is required.
    • b – the argument is treated as an integer and presented as a binary number.
    • c – the argument is treated as an integer and presented as the character with that ASCII value.
    • d – the argument is treated as an integer and presented as a (signed) decimal number.
    • e – the argument is treated as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point since PHP 5.2.1. In earlier versions, it was taken as number of significant digits (one less).
    • E – like %e but uses uppercase letter (e.g. 1.2E+2).
    • f – the argument is treated as a float and presented as a floating-point number (locale aware).
    • F – the argument is treated as a float and presented as a floating-point number (non-locale aware). Available since PHP 5.0.3.
    • g – shorter of %e and %f.
    • G – shorter of %E and %f.
    • o – the argument is treated as an integer and presented as an octal number.
    • s – the argument is treated as and presented as a string.
    • u – the argument is treated as an integer and presented as an unsigned decimal number.
    • x – the argument is treated as an integer and presented as a hexadecimal number (with lowercase letters).
    • X – the argument is treated as an integer and presented as a hexadecimal number (with uppercase letters).

Variables will be co-erced to a suitable type for the specifier :

Type Handling

Type, Specifiers
string , s
integer , d , u, c, o, x, c, o , x, X , b
double , g , G, e, E, f , F

Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results

The format string supports argument numbering/swapping.


Related articles  : echo(), print(), flush(), sprintf(), fprintf(), vprintf(), sscanf(), fscanf(), number_format().


printf() – PHP Functions Example 1 : Various examples
<?php
$n =  23457274;
$u = -23457274;
$c = 66; // ASCII 65 is 'A'

// notice the double %%, this prints a literal '%' character
printf("%%b = '%b'\n", $n); // binary representation
printf("%%c = '%c'\n", $c); // print the ascii character, same as chr() function
printf("%%d = '%d'\n", $n); // standard integer representation
printf("%%e = '%e'\n", $n); // scientific notation
printf("%%u = '%u'\n", $n); // unsigned integer representation of a positive integer
printf("%%u = '%u'\n", $u); // unsigned integer representation of a negative integer
printf("%%f = '%f'\n", $n); // floating point representation
printf("%%o = '%o'\n", $n); // octal representation
printf("%%s = '%s'\n", $n); // string representation
printf("%%x = '%x'\n", $n); // hexadecimal representation (lower-case)
printf("%%X = '%X'\n", $n); // hexadecimal representation (upper-case)
printf("%%+d = '%+d'\n", $n); // sign specifier on a positive integer
printf("%%+d = '%+d'\n", $u); // sign specifier on a negative integer
?>

Output of above code in the browser is as below:

%b = ‘1011001011110110111111010’
%c = ‘B’
%d = ‘23457274’
%e = ‘2.345727e+7’
%u = ‘23457274’
%u = ‘18446744073686094342’
%f = ‘23457274.000000’
%o = ‘131366772’
%s = ‘23457274’
%x = ‘165edfa’
%X = ‘165EDFA’
%+d = ‘+23457274’
%+d = ‘-23457274’

printf() – PHP Functions Example 2 : string specifiers
<?php
$s = 'Tutorial';
$t = 'many Tutorials';
printf("[%s]\n",      $s); // standard string output
printf("[%15s]\n",    $s); // right-justification with spaces
printf("[%-15s]\n",   $s); // left-justification with spaces
printf("[%015s]\n",   $s); // zero-padding works on strings too
printf("[%'#15s]\n",  $s); // use the custom padding character '#'
printf("[%15.15s]\n", $t); // left-justification but with a cutoff of 15 characters
?>

Output of above code in the browser is as below:

[Tutorial]
[ Tutorial]
[Tutorial ]
[0000000Tutorial]
[#######Tutorial]
[ many Tutorials]

printf() – PHP Functions Example 3 : zero-padded integers
<?php
echo $isodate = sprintf("%04d-%02d-%02d", '2019', '2', '4');
?>

Output of above code in the browser is as below:

2019-02-04

printf() – PHP Functions Example 4 : scientific notation
<?php
$number = 2398675000;
echo sprintf("%.3e", $number); 
?>

Output of above code in the browser is as below:

2.399e+9

printf() – PHP Functions Example 5 : formatting currency
<?php
$strMoney1 = 34.75;
$strMoney2 = 89.35;
$sumMoney = $strMoney1 + $strMoney2;
$formatted = sprintf("%01.2f", $sumMoney);
echo $formatted;
?>

Output of above code in the browser is as below:

124.10

jyoti rani

Recent Posts

What Is a Progressive Web App? Why Would You Need One?

App usage is growing steadily without showing any signs of slowing down. Hence, it is no surprise that mobile applications…

11 months ago

7 Most Popular Paid Online Advertising Strategy

As the world has grown more digital, businesses have adapted themselves. An effectual adaptation includes online advertising. Offline advertising styles…

1 year ago

The Importance of User-Centered Design in Mobile App Development

Step into a world where apps dance to the user's tune. Picture Instagram, a photo-sharing sensation that swept the globe.…

1 year ago

Healthcare Mobile App Development: A Complete Guide for Founders

COVID-19 has led to a digitalization of lifestyle. As patients are taking their mental and physical health more seriously, healthcare…

1 year ago

Exploring Diverse WordPress Theme Niches: A Comprehensive Guide

Introduction WordPress, an immensely popular content management system (CMS), powers over 40% of the internet. What makes WordPress even more…

1 year ago

8 Awesome Blog Content Ideas for Movers to Skyrocket the SEO

For moving companies trying to capture their market share amidst stiff competition, a tip or two about what they can…

1 year ago