Printf Function in PHP

printf() Output Formatting


boolean printf (string format [, mixed args])

Printf() output a formatted string that specified in args, except that the output is formatted according to format.

printf( "I'm a %s", "Developer" ); // Developer

The % sign indicates that we are splicing some data into the string, and the s character indicates that we are splicing in a string. The part of the string that begins with % is called the format specifier. And the apostrophe (')  will use to display the different character. The argument consists below components.

  • Padding specifier – Control outcome string size.The default is a space character.
  • Precision specifier – Number of decimal digits, to display accepts only float type.
  • Alignment specifier – Controls the outcome result whether it should be right or left justified.
  • Width specifier – Minimum number of characters, to display.
  • Type specifier – Describe the argument will be cast.

Type Description :
%b   – Presented as a binary number.
%c   – Presented as a character corresponding to that ASCII value.
%d  – Presented as a signed decimal number.
%f   – Presented as a floating-point number,  Default to a precision of 6 decimal places.
%o  – Presented as an octal number.
%s  – Presented as a string.
%u  – Presented as an unsigned decimal number.
%x  – Presented as a lowercase hexadecimal number.
%X  – Presented as an uppercase hexadecimal number.

Padding Specifier :

printf("%.7s",'Programmer'); // Program (Control the output string characters)

Alignment specifier :

printf("%'#15s","Program");  // ########Program
printf("%'#-15s","Program"); // Program######## (Negative adds the padding to right (-))

Precision specifier:

printf("%.1f",450.00); // 450.0
printf("%.5f",450.00); // 450.00000

Width Specifier :

printf("%20s", "Programmer"); //  Programmer (The blank spaces go at the beginning, by default)

Type Specifier:

printf(" Integer Refers - Octal : %o, Binary : %b, Decimal : %d, Floating Points : %f, Hex decimal : %x " , 25,25,25,25,25);
 //Integer Refers - Octal : 31, Binary : 11001, Decimal : 25, Floating Points : 25.000000, Hex decimal : 19