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
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
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.