[ Team LiB ] Previous Section Next Section

Code Blocks and Browser Output

In Hour 3, "A First Script," we established that you can slip in and out of HTML mode at will, using the PHP start and end tags. In this chapter you have discovered that you can present distinct output to the user according to a decision-making process you can control with if and switch statements. In this section, we will combine these two techniques.

Imagine a script that outputs a table of values only when a variable is set to the Boolean value true. Listing 5.13 shows a simplified HTML table constructed with the code block of an if statement.

Listing 5.13 A Code Block Containing Multiple print() Statements
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 5.13 A Code Block Containing Multiple print() statements</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $display_prices = true;
12:
13: if ( $display_prices ) {
14:   print "<table border=\"1\">";
15:   print "<tr><td colspan=\"3\">";
16:   print "todays prices in dollars";
17:   print "</td></tr><tr>";
18:   print "<td>14</td><td>32</td><td>71</td>";
19:   print "</tr></table>";
20: }
21:
22: ?>
23: </div>
24: </body>
25: </html>

If $display_prices is set to true in line 11, the table is printed. For the sake of readability, we split the output into multiple print() statements, and once again we escape any quotation marks. There's nothing wrong with that, but we can save ourselves some typing by simply slipping back into HTML mode within the code block. In Listing 5.14, we do just that.

Listing 5.14 Returning to HTML Mode Within a Code Block
 1: <!DOCTYPE html PUBLIC
 2:   "-//W3C//DTD XHTML 1.0 Strict//EN"
 3:   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 4: <html>
 5: <head>
 6: <title>Listing 5.14 Returning to HTML Mode Within a Code Block</title>
 7: </head>
 8: <body>
 9: <div>
10: <?php
11: $display_prices = true;
12:
13: if ( $display_prices ) {
14: ?>
15:   <table border="1">
16:   <tr><td colspan="3">todays prices in dollars</td></tr><tr>
17:   <td>14</td><td>32</td><td>71</td>
18:   </tr></table>
19: <?php
20: }
21:
22: ?>
23: </div>
24: </body>
25: </html>

The important thing to note here is that the shift to HTML mode on line 14 occurs only if the condition of the if statement is fulfilled. This can save you the bother of escaping quotation marks and wrapping your output in print() statements. It might, however, affect the readability of your code in the long run, especially as your script begins to grow.

    [ Team LiB ] Previous Section Next Section