Code Blocks and Browser Output


In Chapter 4, "Installing and Configuring PHP," you learned 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 that we 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 6.13 shows a simplified HTML table constructed with the code block of an if statement.

Listing 6.13. A Code Block Containing Multiple echo Statements
 1: <?php 2: $display_prices = true; 3: if ($display_prices) { 4:     echo "<table border=\"1\" cellpadding=\"4\" cellspacing=\"4\">\n"; 5:     echo "<tr><td colspan=\"3\">"; 6:     echo "today's prices in dollars"; 7:     echo "</td></tr>"; 8:     echo "<tr><td>\$14.00</td><td>\$32.00</td><td>\$71.00</td></tr>\n"; 9:     echo "</table>"; 10: } 11: ?> 

If the value of $display_prices is set to TRue in line 2, the table is printed. For the sake of readability, we split the output into multiple echo() statements, and once again escape any quotation marks used in the HTML output.

Put these lines into a text file called testmultiecho.php, and place this file in your Web server document root. When you access this script through your Web browser, it should look like Figure 6.2.

Figure 6.2. Output of testmultiecho.php.


There's nothing wrong with the way this is coded, but we can save ourselves some typing by simply slipping back into HTML mode within the code block. In Listing 6.14 we do just that.

Listing 6.14. Returning to HTML Mode Within a Code Block
 1: <?php 2: $display_prices = true; 3: if ($display_prices) { 4: ?> 5: <table border="1" cellpadding="4" cellspacing="4"> 6: <tr><td colspan="3">today's prices in dollars</td></tr> 7: <tr><td>$14.00</td><td>$32.00</td><td>$71.00</td></tr> 8: </table> 9: <?php 10: } 11: ?> 

The important thing to note here is that the shift to HTML mode on line 4 occurs only if the condition of the if statement is fulfilled. This can save us the bother of escaping quotation marks and wrapping our output in echo() statements. It might, however, affect the readability of the code in the long run, especially if the script grows larger.



Sams Teach Yourself PHP MySQL and Apache All in One
Sams Teach Yourself PHP, MySQL and Apache All in One (4th Edition)
ISBN: 067232976X
EAN: 2147483647
Year: 2003
Pages: 333
Authors: Julie Meloni

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net