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.

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 multipleecho() 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.

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.