Prev | Current Page 137 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"

When the printf() statement executes,
the lone argument, 100, will be inserted into the placeholder. Remember that an integer
is expected, so if you pass along a number including a decimal value (known as a float),
it will be rounded down to the closest integer. If you pass along 100.2 or 100.6, 100 will
64 CHAPTER 3 ?–  PHP B ASICS
be output. Pass along a string value such as "one hundred", and 0 will be output. Similar
logic applies to other type specifiers (see Table 3-1 for a list of commonly used specifiers).
So what do you do if you want to pass along two values? Just insert two specifiers
into the string and make sure you pass two values along as arguments. For example, the
following printf() statement passes in an integer and float value:
printf("%d bottles of tonic water cost $%f", 100, 43.20);
Executing this command produces the following:
100 bottles of tonic water cost $43.20
When working with decimal values, you can adjust the precision using a precision
specifier. An example follows:
printf("$%.2f", 43.2); // $43.20
Still other specifiers exist for tweaking the argument??™s alignment, padding, sign,
and width. Consult the PHP manual for more information.
Table 3-1. Commonly Used Type Specifiers
Type Description
%b Argument considered an integer; presented as a binary number
%c Argument considered an integer; presented as a character corresponding to that
ASCII value
%d Argument considered an integer; presented as a signed decimal number
%f Argument considered a floating-point number; presented as a floating-point number
%o Argument considered an integer; presented as an octal number
%s Argument considered a string; presented as a string
%u Argument considered an integer; presented as an unsigned decimal number
%x Argument considered an integer; presented as a lowercase hexadecimal number
%X Argument considered an integer; presented as an uppercase hexadecimal number
CHAPTER 3 ?–  PHP BASICS 65
The sprintf() Statement
The sprintf() statement is functionally identical to printf() except that the output is
assigned to a string rather than rendered to the browser.


Pages:
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149