PHP vprintf() Function
Definition
The vprintf() function outputs a formatted string. Unlike printf(), the arguments in vprintf(), are placed in an array.
Syntax
PHP vprintf() Function has the following syntax.
vprintf(format,argarray)
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.
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
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.
Related functions
sprintf(), printf(), vsprintf(), fprintf() and vfprintf().
Return
PHP vprintf() Function returns the length of the outputted string.
Example 1
Output a formatted string:
<?php// ww w . j a v a 2 s. c om
$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.
Example 2
Using the format value %f:
<?php// w w w . j a va 2 s.c o m
$num1 = 123;
$num2 = 456;
vprintf("%f%f",array($num1,$num2));
?>
The code above generates the following result.
Example 3
Use of placeholders:
<?php/*from ww w . j a v a 2 s . co m*/
$number = 123;
vprintf("With 2 decimals: %1\$.2f
\nWith no decimals: %1\$u",array($number));
?>
The code above generates the following result.