Writing Content
These tutorials are about PHP and its use for server-side Web programming.
Writing Content with PHP
One of the most commonly used features of PHP is to write content out for display over the Web. It can take data from most any data source and with proper coding format it for display in a Web browser.
PHP is designed to run on the server, behind the scenes. Not only should it not display in the Web browser window, but if someone views the source code for a PHP generated document that is currently displayed in their Web browser, the code should not be visible there either. Unless there is an error and the subsequent generation of an error message, a user should never see the PHP code. The PHP code is stripped from the document before it is sent to the user.
The way PHP works in a Web document is by treating the document it is embedded in as an output file. It inserts it output at the location in the code where the script is place. In other words, the output from the script replaces the script before the document is sent on to the user.
We have already encountered one way to do this sort of dynamic document generation with PHP using the echo statement. It echoes the content back to the current document. But PHP has more ways to write output than that. The statements used to write content back to the document in PHP are as follows:
echo
print()
printf()
sprintf()
print_r()
var_dump()
echo
echo is perhaps the most common command for writing output back to the containing document for transmission to the client. Unlike the other print commands, it is not a function. Rather it is a language construct. In other words it is a command that is used like an operator, rather than a function.
You will often see echo written to look like a function call, with parentheses after it, echo ($someVar);. The parentheses help to organize the code and are useful for marking the limits of longer strings and concatenations, but the parentheses are optional, and are even not allowed in some circumstances.
The echo command writes the values of one or more arguments to the screen. If there is more than one argument, then the arguments must occur in a comma separated list. Although the individual elements can have parentheses around them for grouping, the entire list cannot. This is, incidentally, because parentheses have a higher order of precedence than the echo command, so the parser would try to parse the comma separated list as an expression and pass the results to the command.
Correctly formed echo commands.
echo $myVar;
echo ($myVar);
echo $myVar, $myOtherVar;
echo ($myVar), ($myOtherVar);
Incorrectly formed echo commands.
// parentheses cant be used this way
echo ($myVar, $myOtherVar);
// needs a separator between arguments
echo $myVar $myOtherVar;
// wrong separator between arguments
echo $myVar; $myOtherVar;
The echo command writes out the arguments to the document in the order in which they occur in the statement.
print()
The print() command is a proper function and requires the parentheses after it. Unlike the echo command, it only takes a single argument. This argument is written out to the document being processed.
The print() command will also return a value of true or false so you can test whether the output was successfully generated.
Formatting Output
PHP allows two variations on the C-style printf() commands, the printf() command itself and the sprintf(). Both allow you to format output strings based on formatting arguments passed to the function. Thus you can do things like specify alignment, padding characters, precision, and numbering system to display with.
The sprintf() command does the same thing as the printf() command, except that instead of return the results to the output document, it returns the results to be assigned to some variable. This allows you to then use the formatted output string in echo and print() statements. So aside from a coding example, nothing more needs to be said about it.
$myOut = sprintf('%.2f', $myNum);
echo "This number has two decimal places: " . $myOut;
So how does printf() work? It works by taking two or more arguments which determine how the output string is to be generated. The first argument is the formatting string, which is a template that specifies how the output is to be formatted. The second argument and all other arguments after the second are data elements to be inserted into the output string where specified in the formatting string.
printf('template', 'data'[...]);
printf('%d equal %x hex', 200, 200);
printf('%0.6f', $fpNum);
The purpose of the printf() statement is to format output for display. Since we are talking about PHP in the context of Web development, its most common use for us is to format floating point numbers, but it has a wide variety of uses:
- Displaying integers in decimal, octal, or hexadecimal format.
- Insert values into string literals.
- Specify the sign of values.
- Set precision (the number of decimal places) in floating point numbers.
- Round floating point numbers.
- Set fixed width data fields.
The key element in the printf() statement is the formatting string. It contains one or more substition markers that specify what to do with the arguments that follow the formatting string. There should be one data element for each substitution marker. Each substitution maker begins with a percent sign ( % ) and ends with a character that indicates the display type for the data. Between the percent sign and the display type there can be a series of formatting modifiers that specify the formatting features of the output string.
Formatting Modifiers
The formatting modifier change how the formatted output element is displayed. They are not required if the default settings are satisfactory for a given display type are satisfactory. If they are included, they must occur in the following order.
- padding character
-
Sometimes you want to format elements so that they have some padding before or after them. The padding character allows you to specify what this is. The length and precision of the string are defined later. The padding character can have the following values:
0 (zero) -- a zero in this position indicates that the content, presumably a number, should be padded with leading zeros if shorter than the minimum display length or with trailing zeros if the precision is greater than the actual number of values after the decimal place. If you do not specify a length or a precision, then no padding will take place.
(a blank space) -- a blank space in this position indicates that padding should be done with spaces. This is the default, so you don't actually have to specify it.
'x -- a single quote followed by some character specifies the character after the quote as being the padding character. In this case, the X would be a padding character..
- sign
- The sign indicator is not exactly what it seems. What it does depends on the sign use. A minus sign (
- ) right justifies the output string, assuming the string is shorter than the specified length. A plus sign ( + ) forces a leading plus sign to appear in front of positive numbers.
- length
- The length is a number that represents the minumum number of characters to output. The string will be padded to fit. The direction of the padding depends on the data type and the sign operator.
- precision
- Precision only applies to floating point numbers and is used to specify how many positions to specify after the decimal place. It is represented by a period followed by a number representing the number of places desired.
An example using all of the formatting modifiers in a single statement:
printf('The answer is %0+6.4f', $result);
Another example:
printf("% 15S %'.-25d", $title, $page);
// which by the way would print the following
// for a table of contents or similar
// Some Title .......................##
Also, if the percent sign is an operator in this situation, then how do you print a percent sign? You do this by putting two percent signs in the formatting string where you want the percent to occur.
printf('%d%%', 25)
// results is "25%"
Type Specifiers
The type specifier allows you to specify the data type the output string is supposed to represent. The data type of the output is actually a string, but the type specifier allows you to specify that the formatting in the string be appropriate to a given data type. For instance, you can specify that the output from the substition be formatted as an integer, or a hexadecimal number, or a floating point number with or without scientific format.
The type specifer must always be the last character as that it terminates the substitution string. Its values are as follows:
- Strings
- There is only one string specifer,
S. The letter is capitalized. It is used to print out non-numeric values.
- Integers
-
To display integers, any of the following values can be used:
d -- display a decimal integer
I -- display as decimal integer
U -- display as unsigned integer
B -- display as a binary value
O -- (capital letter O) -- display as an octal value
x -- display as a hexadecimal value with lower case letters
X -- display as a hexadecimal value with upper case letters
- Floating-Point Numbers
-
To disaply floating-point numbers any of the following can be used:
f -- display as a floating-point number in standard decimal notation
E -- display as floating-point number in scientific notation
e -- same
G -- if the requestion precision is greater than or equal to the precision of the value to be written, then use standard decimal notation, otherwise use scientific notation
g -- same
Data Dumps
Sometimes you are writing code that is not meant to format something nicely for the screen, but rather to display the values of elements within the code so that you can debug or track your scripts. PHP provides two commands to do this, print_r() and var_dump().
Both attempt to display any variable passed to it, including arrays and objects, in a meaningful fashion. The other output statements will just print the string "Array" for arrays and "Object" for objects.
If you are using print_r() on an array, be aware of the fact that it does move the pointer indicating current array position to the end of the array. So of you are going to use that array later in the code, it will need to be reset.
Also, be careful not to use print_r if there is any chance of the structure you are referencing being recursive. Some objects do contain references back to themselves. This will yield an infinite loop. var_dump() is a little smarter. If it finds itself recursing, it stops after the third iteration.
What follows is a comparision of outputs for the different output statements (excluding printf()) so you can see how the deal with different data types. Note that if you use print_r() or var_dump() to write to a Web page, you need to put the output in <pre> tags to look like this, otherwise it will run together. This is because, as with anything in an HTML document, white space is ignored unless the browser is told otherwise.
What is represented here is the output of:
- a boolean,
- a floating-point number,
- a string,
-
- an array,
- and an object.
These are our test variables:
// a boolean
$testB = true;
// a floating-point number
$testN = 1.21715e12;
// a string
$testS = 'a test string';
// an array
$testA = array(1, 2, 3, 'cat', 'dog', 'bird');
// an object
class someObj {
var $a = 10;
var $b = '2';
function ret_20() { return ($this->a * $this->b); }
}
$testO = new someObj;
Output from echo
// a boolean
1
// a floating-point number
1.21715E+012
// a string
a test string
// an array
Array
// an object
Object
Output from print()
// a boolean
1
// a floating-point number
1.21715E+012
// a string
a test string
// an array
Array
// an object
Object
Output from print_r()
// a boolean
1
// a floating-point number
1.21715E+012
// a string
a test string
// an array
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => cat
[4] => dog
[5] => bird
)
// an object
someobj Object
(
[a] => 10
[b] => 2
)
Output from var_dump()
// a boolean
bool(true)
// a floating-point number
float(1.21715E+12)
// a string
string(13) "a test string"
// an array
array(6) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(3)
[3]=>
string(3) "cat"
[4]=>
string(3) "dog"
[5]=>
string(4) "bird"
}
// an object
object(someobj)(2) {
["a"]=>
int(10)
["b"]=>
string(1) "2"
}
These pages can be found at:
[http://academ.hvcc.edu/~kantopet/]
Copyright 2003 -- Peter L. Kantor[kantopet@hvcc.edu]
Last Updated January 2003