The vprintf() function outputs a formatted string. Unlike printf(), the arguments in vprintf(), are placed in an array.
PHP vprintf() Function has the following syntax.
vprintf(format,argarray)
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.
Format | Meaning |
---|---|
%% | 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 |
%u | Unsigned 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 values are placed between the % and the letter (example %.2f):
Additional format | Meaning |
---|---|
+ | 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.
sprintf(), printf(), vsprintf(), fprintf() and vfprintf().
PHP vprintf() Function returns the length of the outputted string.
Output a formatted string:
<?php/* w w w . ja va 2s.co m*/
$number = 2;
$str = "PHP";
vprintf("There are %u million developers using %s.",array($number,$str));
$str1 = "Hello";
$str2 = "Hello world!";
vprintf("[%s]\n",array($str1));
vprintf("[%8s]\n",array($str1));
vprintf("[%-8s]\n",array($str1));
vprintf("[%08s]\n",array($str1));
vprintf("[%'*8s]\n",array($str1));
vprintf("[%8.8s]\n",array($str2));
?>
The code above generates the following result.
Using the format value %f:
<?php
$num1 = 123;
$num2 = 456;
vprintf("%f%f",array($num1,$num2));
?>
The code above generates the following result.
Use of placeholders:
<?php
$number = 123;
vprintf("With 2 decimals: %1\$.2f
\nWith no decimals: %1\$u",array($number));
?>
The code above generates the following result.