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

Hàm printf() trong PHP

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

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

The printf() 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(), sprintf(), vfprintf(), vprintf() and vsprintf().

The following table summarizes the technical details of this function.

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

Syntax

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

printf(format, arg1, arg2, argN);

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

Example

<?php
// Sample strings
$count = 50;
$country = "United States";
$format = "There are %d states in the %s.";

// Formatting and print the string
printf($format, $count, $country);
?>
 

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 printf() function is identical to sprintf() except that the printf() function outputs a text string directly, similar to the print and echo statements, whereas the sprintf() function returns the formatted string so that you can assign it to a variable.


Parameters

The printf() 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.
arg1 Required. Specifies the argument to be formatted and inserted at the position of first conversion specification in the format string.
arg2 Optional. Specifies the argument to be formatted and inserted at the position of second conversion specification in the format string.
argN Optional. Specifies the argument to be formatted and inserted at the position of Nth conversion specification 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 printf() 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 printf() function actually works:

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

Example

<?php
// Sample string
$str = 'star';
$format = 'The polar %1$s is the brightest %1$s in the sky.';

// Formatting and print the string
printf($format, $str);
?>
 

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.

Example

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

// Formatting and print the string
printf($format, $number);
?>

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

Example

<?php
// Sample strings
$count = 50;
$country = "United States";
$format = "The %2\$s is a federal republic of %1\$d states.";

// Formatting and print the string
printf($format, $count, $country);
?>
 

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 function. You can use argnum to easily indicate which arguments the placeholders refer to and leave the function code as is.

The following example demonstrates the use of various format specifiers for different types of data.

Example

<?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)
?>

The following example shows how to format a string in different ways using s specifier.

Example

<?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