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 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: ?>

Watch Out!

In line 8 you will note the dollar sign, when meant literally and not as part of a variable declaration, must be escaped with a backslash in order for it to be interpreted as the dollar sign character.


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 use the backslash to 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. This approach 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 (3rd Edition)
ISBN: 0672328739
EAN: 2147483647
Year: 2004
Pages: 327

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