Monday, February 20, 2006

Formatting output

PHP was designed specifically for the World Wide Web and its screen output is formatted as HTML. If there's an exception to that, I haven't seen it yet. But HTML doesn't always appear on the screen the way you want it to. Well, not without a little help, anyway.

Let's say you wanted to put a specific number of blank spaces in your output. (Don't forget that the width of a space isn't always the same unless you specify a monospace font...). The problem with most HTML code is that it converts a string of spaces to a single space unless you tell it otherwise.

There's a tag you can use for "preformatted output" that will override the tendency of HTML to eat the extra spaces. Here's an example where I'm showing a script and I want the indenting:

<PRE>
function runForever() {
if(6 == 9) {
print("Warning! Infinite loop");
}
}</PRE>

Everything between the <PRE> and </PRE> tags has the same spacing and line feeds as it would have coming out of a word processor or typewriter. To be able to show you the <PRE> and </PRE> tags themselves, I had to enter them using HTML entities so they wouldn't be interpreted as tags!

Other ways to format text on the screen include using printf() and sprintf() just like in the C language. You can make numbers and text appear in a field of a certain width, choose a character to pad out the unused spaces and make your numbers appear as integers(binary, decimal, hex or octal), doubles (floating point values such as 3.14159) or doubles in scientific notation.

Text can be right- or left-justified and you can pass ASCII codes for characters and get the characters on the screen. Full documentation and a lot of good examples can be found here:

http://us3.php.net/manual/en/function.sprintf.php

Happy Coding!