Specifications
Both of these techniques print a string “as is.” You can apply some more sophisticated format-
ting using the functions printf() and sprintf(). These work basically the same way, except
that printf() prints a formatted string to the browser and sprintf() returns a formatted
string.
If you have previously programmed in C, you will find that these functions are the same as the
C versions. If you haven’t, they take getting used to but are useful and powerful.
The prototypes for these functions are
string sprintf (string format [, mixed args...])
int printf (string format [, mixed args...])
The first parameter passed to both these functions is a format string that describes the basic
shape of the output with format codes instead of variables. The other parameters are variables
that will be substituted in to the format string.
For example, using
echo, we used the variables we wanted to print inline, like this:
echo “Total amount of order is $total.”;
To get the same effect with printf(), you would use
printf (“Total amount of order is %s.”, $total);
The %s in the format string is called a conversion specification. This one means “replace with a
string.” In this case, it will be replaced with $total interpreted as a string.
If the value stored in $total was 12.4, both of these approaches will print it as 12.4.
The advantage of printf() is that we can use a more useful conversion specification to specify
that $total is actually a floating point number, and that it should have two decimal places after
the decimal point, as follows:
printf (“Total amount of order is %.2f”, $total);
You can have multiple conversion specifications in the format string. If you have n conversion
specifications, you should have n arguments after the format string. Each conversion specifica-
tion will be replaced by a reformatted argument in the order they are listed. For example
printf (“Total amount of order is %.2f (with shipping %.2f) “,
$total, $total_shipping);
Here, the first conversion specification will use the variable $total, and the second will use
the variable $total_shipping.
Each conversion specification follows the same format, which is
%[‘padding_character][-][width][.precision]type
Using PHP
P
ART I
98
06 7842 CH04 3/6/01 3:41 PM Page 98