Hướng dẫn
Quảng cáo

Hàm vprintf() trong PHP

Hướng dẫn cách sử dụng hàm vprintf() trong lập trình PHP

Tác dụng của hàm vprintf()

The vprintf() function outputs a formatted string.

This function takes a special format string and then any number of other arguments, which will be formatted and spliced into the specified places in the format string to generate the result.

Related functions: fprintf(), printf(), sprintf(), vfprintf() and vsprintf().

The following table summarizes the technical details of this function.

Return Value: Returns the length of the outputted string.
Version: PHP 4.1.0+

Syntax

The basic syntax of the vprintf() function is given with:

vprintf(format, argument_array);

The following example shows the vprintf() function in action.

<?php
// Sample array
$argarray = array("50", "United States");

// Defining the format string
$format = "There are %d states in the %s.";

// Formatting and print the string
vprintf($format, $argarray);
?>

Note: Every character in the format string will be printed literally, except the % character and characters that immediately follow it. The % character indicates the beginning of a conversion specification, which specifies how to print the arguments that follow the format string.

Tip: The vprintf() function is identical to printf(), with one exception. The vprintf() function accepts an array of arguments, whereas the printf() accepts a list of arguments.


Parameters

The vprintf() function accepts the following parameters.

Parameter Description
format Required. Specifies the format string. It is composed of ordinary characters (excluding %) and one or more conversion specifications.
argument_array Required. Specifies an array of arguments that is to be formatted and inserted at the positions of conversion specifications in the format string.

Conversion Specification Syntax

This section describes the syntax of conversion specification in the format string in detail.

A conversion specification begins with a percent symbol (%). You must include a conversion specification for each argument that is passed to the vprintf() function after the format string.

Alternatively, you can use the argument number followed by a dollar sign (i.e. argnum$) to apply multiple conversion specifications in the format string to the same argument. It must come immediately after the percent sign (%), before any other specifiers. See more examples section.

A conversion specification typically has the following syntax:

%[argnum$][flags][width][.precision]specifier

argnum

An integer followed by a dollar sign $, to specify which number argument to treat in the conversion.

flags

The flags consist of one or more of the following characters:

Flag Description
+ Adds a plus sign before positive numbers. By default, only negative numbers are marked.
- Left-justify within the given field width; Right justification is the default.
(space) Pads the result with spaces. This is the default.
0 Only left-pads numbers with zeros. With s specifiers this can also right-pad with zeros.
'(char) Pads the result with the character (char). Must be used together with the width specifier.

width

An integer that indicates how many characters (minimum) this conversion should result in.

precision

A period (.) followed by an integer who's meaning depends on the specifier:

  • For e, E, f and F specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6).
  • For g and G specifiers: this is the maximum number of significant digits to be printed.
  • For s specifier: it acts as a cutoff point, setting a maximum character limit to the string.

If the period is specified without an explicit value for precision, 0 is assumed.

specifier

A single character indicating how the type of the argument should be interpreted.

specifier Description
% A literal percent character. No argument is required.
b The argument is treated as an integer and printed as a binary number.
c The argument is treated as an integer and printed as the character with that ASCII.
d The argument is treated as an integer and printed as a (signed) decimal number.
e The argument is treated as as scientific notation (e.g. 1.2e+2). The precision specifier stands for the number of digits after the decimal point.
E Like the e specifier but uses uppercase letter (e.g. 1.2E+2).
f The argument is treated as as a float and printed as a floating-point number (locale aware).
F The argument is treated as as a float and printed as a floating-point number (non-locale aware).
g General format. Uses e and f.
G Like the g specifier but uses E and f.
o The argument is treated as an integer and printed as an octal number.
s The argument is treated and printed as a string.
u The argument is treated as an integer and printed as an unsigned decimal number.
x The argument is treated as an integer and printed as a hexadecimal number (lowercase letters).
X The argument is treated as an integer and printed as a hexadecimal number (uppercase letters).

More Examples

Here're some more examples showing how vprintf() function actually works:

The following example shows how to apply multiple conversion specifications to the same argument.

<?php
// Sample array
$array = array('star');

// Defining the format string
$format = 'The polar %1$s is the brightest %1$s in the sky.';

// Formatting and print the string
vprintf($format, $array);
?>

Tip: If the format string is enclosed in double-quotes (""), you need to escape the dollar sign after argnum with a backslash character (\), like this %1\$s, so that the PHP doesn't try to interpret them as variable. Using a backslash like this is called an escape sequence.

The following example shows how to format the same number with and without decimal points.

<?php
// Sample array
$array = array(499);

// Defining the format string
$format = "The number without decimal points: %1\$d, and the number with two decimal points: %1\$.2f";

// Formatting and print the string
vprintf($format, $array);
?>

By default, each conversion specification will be replaced by the formatted argument in the order they are listed inside the array. But, you can swap arguments inside the format string using argnum.

<?php
// Sample array
$array = array("50", "United States");

// Defining the format string
$format = "The %2\$s is a federal republic of %1\$d states.";

// Formatting and print the string
vprintf($format, $array);
?>

Tip: If the order of the placeholders or conversion specifications in the format string does not match the order of the arguments listed inside the array. You can use argnum to easily indicate which arguments the placeholders refer to and leave the function code as is.

The following example simply demonstrates what would be the possible outcome when using the different format specifiers for integer values using the printf() function.

<?php
// Sample integers
$num1 = 123456789;
$num2 = -123456789;
$num3 = 65; // ASCII 65 is 'A'

// Notice the double %%, this simply prints a '%' character
printf("%%b = %b <br>", $num1); // Binary representation
printf("%%c = %c <br>", $num3); // The ASCII Character
printf("%%d = %d <br>", $num1); // Standard integer representation
printf("%%d = %d <br>", $num2); // Standard integer representation
printf("%%e = %e <br>", $num1); // Scientific notation (lowercase)
printf("%%E = %E <br>", $num1); // Scientific notation (uppercase)
printf("%%u = %u <br>", $num1); // Unsigned integer representation (positive)
printf("%%u = %u <br>", $num2); // Unsigned integer representation (negative)
printf("%%f = %f <br>", $num1); // Floating-point representation (locale aware)
printf("%%F = %F <br>", $num1); // Floating-point representation (non-locale aware)
printf("%%g = %g <br>", $num1); // Shorter of %e and %f
printf("%%G = %G <br>", $num1); // Shorter of %E and %f
printf("%%o = %o <br>", $num1); // Octal representation
printf("%%s = %s <br>", $num1); // String representation
printf("%%x = %x <br>", $num1); // Hexadecimal representation (lowercase)
printf("%%X = %X <br>", $num1); // Hexadecimal representation (uppercase)
printf("%%+d = %+d <br>", $num1); // Sign specifier (positive)
printf("%%+d = %+d <br>", $num2); // Sign specifier (negative)
?>

Similarly, the following example shows how to format a string in various ways using s specifier.

<?php
$str1 = "Hello";
$str2 = "Hello Alexander!";

printf("[%s]<br>", $str1);     // Standard string output
printf("[%10s]<br>", $str1);   // Right-justifies the string with spaces
printf("[%-10s]<br>", $str1);  // Left-justifies the string value with spaces
printf("[%010s]<br>", $str1);  // Left-pads string with zeros.
printf("[%-010s]<br>", $str1); // Right-pads string with zeros
printf("[%'#10s]<br>", $str1); // Left-pads string with '#' character
printf("[%.10s]<br>", $str2);  // Cuts off string after 10 characters
?>

Bài viết này đã giúp ích cho bạn?

Bài viết mới

Advertisements