Monday, February 20, 2006

More formatting tips

I just answered an email from a friend who had a problem getting the formatting with printf() to work properly. Using printf() and sprintf() can be a little tricky at times so I've made a page with 3 examples of using printf() to print out some formatted text. I'll give you the URL shortly. For now, let's look at John's problem:

(From the email I received)
"I've written a simple little program that outputs
the following:

Free space on drive C: 103.67 GB
Free space on drive C: 106154.02 MB
Free space on drive C: 108701716 KB
Free space on drive C: 111310557184 bytes

Now what I would like for it to do is look like this:
Free space on drive C: 103.67 GB
106154.02 MB
108701716 KB
111310557184 bytes

... instead of getting the above I get this:

Free space on drive C: 103.67
106154.02 MB
108701716 KB
111310557184 bytes

How, then, can I easily achieve the effect of printing
blank space when it must precede anything else on a
line of PHP output?"


The answer, while simple, isn't obvious at all. Here's what happens: The printf() statements he used were correct but the browser ignored the extra spaces. Why? Because HTML only shows one space where it encounters several together - unlesss you specify that you want things another way.

The <PRE> ... </PRE> does that for you. By default, you'll get small text in a monospace font. If you want to change the appearance (size, etc.) you can put a <FONT> ... </FONT> in between the <PRE> ... </PRE> tags.

Like this: <PRE><FONT size=4> ... </FONT></PRE>

Be careful not to use a proportional font. If you do, the characters will have different widths and the spaces won't be as wide as you expect. You'll see how bad this can look when you go to my example page.

I took the example from php.net and made a page that shows the code and the output in three different variations. Two of them look OK; one looks awful.

OK, I've kept you in suspense long enough. Here's the URL:
www.learntousephpintwohours.com/monkey_printf.php

Happy Coding!