Using printf
You’ve already seen the print
and
echo
functions, which simply output
text to the browser. But a much more powerful function, printf
, controls the format of the output by
letting you put special formatting characters in a string. For each
formatting character, printf
expects
you to pass an argument that it will display using that format. For
instance, the following example uses the %d
conversion specifier to display the value
3
in decimal:
printf("There are %d items in your basket", 3);
If you replace the %d
with
%b
, the value 3
will be displayed in binary (11
). Table 7-1 shows the conversion
specifiers supported.
Specifier |
Conversion action on argument arg |
Example (for an arg of 123) |
|
Display a |
|
|
Display |
|
|
Display the ASCII character
for the |
|
|
Display |
|
|
Display |
|
|
Display |
|
|
Display |
|
|
Display |
|
|
Display |
|
|
Display |
|
|
Display |
|
You can have as many specifiers as you like in a printf
function, as long as you pass a matching
number of arguments and as long as each specifier is prefaced by a
%
symbol. Therefore, the following code is valid, ...
Get Learning PHP, MySQL, JavaScript, and CSS, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.