Skip to Main Content
Learning PHP, MySQL, and JavaScript
book

Learning PHP, MySQL, and JavaScript

by Robin Nixon
July 2009
Beginner content levelBeginner
526 pages
14h 24m
English
O'Reilly Media, Inc.
Content preview from Learning PHP, MySQL, and JavaScript

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 would be displayed in binary (11). Table 7-1 shows the conversion specifiers supported.

Table 7-1. The printf conversion specifiers

Specifier

Conversion action on argument arg

Example (for an arg of 123)

%

Display a % character (no arg is required)

%

b

Display arg as a binary integer

1111011

c

Display ASCII character for the arg

{

d

Display arg as a signed decimal integer

123

e

Display arg using scientific notation

1.23000e+2

f

Display arg as floating point

123.000000

o

Display arg as an octal integer

173

s

Display arg as a string

123

u

Display arg as an unsigned decimal

123

x

Display arg in lowercase hexadecimal

7b

X

Display arg in uppercase hexadecimal

7B

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, and will output “My name is Simon. I’m 33 years old, which is 21 in hexadecimal”:

printf("My name is %s. I'm %d years ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Web Database Applications with PHP and MySQL, 2nd Edition

Web Database Applications with PHP and MySQL, 2nd Edition

Hugh E. Williams, David Lane
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 9780596803605Supplemental ContentErrata Page