O'Reilly logo

Learning PHP, MySQL & JavaScript, 4th Edition by Robin Nixon

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 7. Practical PHP

Previous chapters went over the elements of the PHP language. This chapter builds on your new programming skills to teach you some common but important practical tasks. You will learn the best ways to manage string handling to achieve clear and concise code that displays in web browsers exactly how you want it to, including advanced date and time management. You’ll also find out how to create and otherwise modify files, including those uploaded by users.

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required