Home > Articles

Program Input and Output

  • Print
  • + Share This
In this sample chapter, author Toby Butzon disusses the purpose of input and output, revisits output and introduces advanced types, and examines requesting input and input methods.
This sample chapter is excerpted from PHP By Example, by Toby Butzon.
This chapter is from the book

This chapter is from the book

Without input and output, your program might as well be a regular HTML page. When you add input and output, however, your program's potential will be unlimited. You will be able to collect information from your visitors, ask them questions, and give them a personalized experience that you never could have provided before.

This chapter teaches you the following:

  • The purpose of input and output
  • Output as you've already seen it
  • Advanced types of output
  • Requesting input
  • Input methods

Revisiting Output

Output is the text or information that is sent from your program to the user (specifically, the visitor to your Web site). Think of output as anything the user receives from a program.

For example, when you use a search engine, a program performs the search and sends back HTML data that looks to your browser like any other HTML page. The page isn't like other HTML files—it isn't saved anywhere on the server. The program simply sent its output—a customized HTML page—straight to your browser.

Figure 3.1 illustrates the interaction that might occur between your browser and a server when performing such a search.

Figure 3.1 At its most basic level, the interaction between a visitor's browser and your program works like this: A request is sent to the program and the program's output is its response to the browser.

We've already briefly visited one way of sending output—the echo command. Output can be sent in several different ways. The method that you use depends on the context within the program. The following considerations may influence your decision on which method to use:

  • The content may vary from one visitor to the next, or it may always be the same.

  • The length of the content you wish to send as output might be short (one line or a single word), or it could be long (a paragraph, a table, or even a whole file).

The following sections will help you understand when and how to use each method of output.

The echo Command

You should decide which method to use to send output based on what you're sending. You must decide whether the content is static or dynamic. On top of that, if the content is dynamic, you will have to consider how much of it there is to send.

All output can be divided into two main categories: static and dynamic. Static output is output that will not change from visitor to visitor; it is hard-coded within the file and independent of any variables. Dynamic output, on the other hand, is any output that contains variables, may change from visitor to visitor, or depends upon variables in any way.

To help clarify the division, think of it this way: Static output will never change unless someone changes the program itself; dynamic output will change from user to user, from one time to the next, or depending on an outside data source such as a database. Figure 3.2 illustrates this visually.

Figure 3.2 The left side of this diagram shows the interaction between multiple visitors and a program that produces static output; the right side shows multiple visitors interacting with a program that produces dynamic output.

The echo command is an excellent choice for dynamic content. It allows you to output numbers, text, and variables all in one string. While it can be used for static content as well, your HTML code will become less readable if you have to "wrap" it with PHP code (such as enclosing it in quotes). Therefore, echo should only be used to insert small amounts of dynamic content at a time.

The following example demonstrates a PHP program with nothing but static output—it is returned just as a regular HTML file would be

<html>
<head><title>Example Page</title></head>
<body>This is an example!</body>
</html>

Since none of this code is enclosed in PHP tags, every line is sent as output. Also, the output doesn't rely in any way on any variables or data sources, so it is classified as static.

NOTE

Recall from Chapter 1, "Welcome to PHP," that anything outside of PHP tags is sent straight to output without being processed in any way. Even if a variable is inserted into this code, it would not be interpreted as a variable; rather, the text would be sent just as it appeared.

The following program sends the same result (also static output), but this time uses echo:

<?php
/* ch03ex01.php – demonstrates static output with echo */

echo "<html>\n";
echo "<head><title>Example Page</title></head>\n";
echo "<body>This is an example!</body>\n";
echo "</html>\n";

?>

NOTE

The \n is interpreted as a symbol (called an escape sequence); it means newline and is sometimes also called the newline character. It is comparable to pressing Enter on your keyboard. Without the newlines, all of the outputted HTML code for the previous example would appear on a single line because echo alone doesn't add anything to separate the lines.

This example uses echo in a way that is understandable to PHP but more complicated than most people prefer to read. Look at the first example and then again at the second; in this case, there's no good reason to add all of the extra echo commands, quotes, and newline characters.

Also, according to our basic classification of echo, it should only be used for short, dynamic output. Since this output is long and static, it would be better to stick with the method used in the first example by placing the text outside of the PHP tags.

Now let's take a look at a more appropriate use of echo. The following example is a mostly static HTML page with a small portion of dynamic content—therefore, a small section of PHP code and an echo statement are inserted to output the contents of a variable ($aVariable):

<?php
/* ch03ex02.php – demonstrates dynamic output with echo */

$aVariable = "This is a variable!";

?>
<html>
<head><title>Example: Static vs. Dynamic Output</title></head>
<body>

<b>Static output:</b><br>
The following is static output. It will never change.<br>
Here's a variable: $aVariable<br><br>

<b>Dynamic output:</b><br>
The following is dynamic output. It may change.<br>
<?php

echo "Here's a variable: $aVariable";

?>

</body>
</html>

Here's the output:

<html>
<head><title>Example: Static vs. Dynamic Output</title></head>
<body>

<b>Static output:</b>
This is static output. It will never change.<br>
Here's a variable: $aVariable<br><br>

Dynamic output:<br>
This is dynamic output. It may change.<br>
Here's a variable: This is a variable!

</body>
</html>

NOTE

This output is the HTML code you would see if you used your browser's View Source feature.

The only text the user would actually see in his browser would be

Static output:
This is static output. It will never change.
Here's a variable: $aVariable

Dynamic output:
This is dynamic output. It may change.
Here's a variable: This is a variable!

From the previous example you should recall that PHP doesn't interpret text placed outside of the PHP tags at all. So, the text "$aVariable" was output just as it appeared in the code when it was outside of the PHP tags. However, when it was mentioned inside the tags in a double-quoted string it was interpreted as a variable and the value of that variable was output instead of the actual text "$aVariable."

This is a more appropriate use of echo; notice that only a single line (the one with the variable) was sent with echo. The rest of the output was sent as static output. It will never change and therefore doesn't need echo.

CAUTION

If the strings following echo in the previous example had been single quoted, they would not have been interpreted, and the static output and dynamic output would look the same.

Using Here-doc

So far you've seen output sent by placing it outside of the PHP tags and output sent using one-line echo statements. Now lets take a look at ways to send large amounts of dynamic output without the tediousness and confusion of using multiple echo statements. This is important: In the future, you might find yourself writing programs in which more than 75% of the program is dynamic output.

There are two ways to send large amounts of dynamic output: Use a single echo statement, thereby reducing the clutter of outputting multiple lines of data with echo, or use static output and insert PHP tags to print variables wherever necessary.

The first method is called here-doc (short for "here-document"). Here-doc helps you, the programmer, create clearer multiline strings; it behaves just as a double-quoted string would, but in a more readable fashion. It also allows you to use only one echo statement, as opposed to the clutter of repeated echo statements.

PHP understands and executes the following code, but because the string might not end for many lines and because any double quotes within the string must be escaped, the purpose and contents of the string can become unclear:

<?php
/* ch03ex03.php – demonstrates multi-line double-quoted string */

// Multi-line double-quoted string
echo "<html>
<head><title>Example</title></head>
<body>
This is an example!
</body>
</html>";

?>

Here-doc allows the code to use more understandable multiline strings. First, by using here-doc, you're saying, "Heads up! I'm using a multiline string here." If you take a look at the double-quoted string shown previously, that's not suggested in any way; in fact, if you saw the following line alone, you would think that it was erroneous:

echo "<html>

Using double quotes to create multiline strings is hard to understand just for this reason. There's nothing to say that the string is multiline other than the fact that it isn't ended with a double quote. You or someone reading your code might find themselves asking, "Did he mean to do that?"

There's another reason that here-doc is better than double quotes. Whereas, the double quote at the end of a multiline string doesn't mean much to anybody except "this is the end of a string," here-doc allows you to specify an end identifier that can be descriptive of the string's purpose or contents.

Here's an example of a here-doc statement:

<?php
/* ch03ex04.php – demonstrates use of here-doc */

// Set $user and $pass variables
$user = "John Doe";
$pass = "doe123";

// Outputting a multi-line here-doc string
echo <<<END_USER_INFO
Username: $user<br>
Password: $pass
END_USER_INFO;

?>

The <<< syntax is used exclusively for here-doc. The first line might be read: "echo everything until END_USER_INFO is reached."

NOTE

END_USER_INFO just happens to be the end identifier I chose; while it is appropriate for its descriptiveness of the string, it could have been any other string following the end identifier naming convention, which follows.

Like constants and variables, end identifiers for here-doc strings follow a naming convention. Typically, they are uppercase strings with any multiple words separated by underscores. The convention itself dictates that identifiers can be any combination of letters (upper- and lowercase), numbers, and underscores. However, an end identifier should not contain spaces or begin with a number.

Notice that here-doc strings are interpreted just as double-quoted strings are: Variables are replaced with their values and escape sequences (such as \n) still work.

NOTE

Double quotes in here-doc strings can be escaped, but it isn't necessary as it is in a double-quoted string.

You must place the ending identifier for a here-doc string at the very beginning of a new line. This makes here-doc strings more efficient for PHP to interpret because PHP only has to look for the end identifier at each new line as opposed to every position of every line. However, if you forget to place the end identifier at the leftmost position on a line, you will find yourself trying to figure out an error message for a line that seems to have nothing wrong with it; in fact, it probably doesn't. Make sure any here-doc statements before it are terminated correctly. Remembering this can save you much frustration.

Take a look at the following code, which directly compares the use of a double-quoted string to a here-doc string:

<?php
/* ch03ex05.php – compares use of double-quoted string to here-doc */

// Multi-line double-quoted string
echo "<body bgcolor=\"#FFFFFF\" text=\"#000000\">
This is an example!<br>
Here's a variable: $aVariable<br>

</body>";

// Multi-line here-doc string
echo <<<END_OF_OUTPUT
<body bgcolor="#FFFFFF" text="#000000">
This is an example!<br>
Here's a variable: $aVariable<br>

</body>
END_OF_OUTPUT;

?>

These examples have the exact same output. However, you should notice how difficult it could be to read a multiline string when the double-quotes must be escaped. With too much escaping, your strings would, at times, become almost impossible to comprehend. Since here-doc doesn't require quotes to be escaped, it can make your code easier to read.

Using Short Tags

The other method of outputting large amounts of dynamic data is to use short tags. As discussed in Chapter 1, short tags are a shorthand way to make regular PHP tags shorter.

The following example uses the short tag that you've already seen:

<? echo "This echo statement is in short tags!"; ?>

NOTE

Recall from Chapter 1 that using short tags shortens the first tag because you remove the letters "php" from it; the closing tag remains the same. Also, the semicolon following the command shown here can be omitted because it is the only command within the PHP tags.

Using an echo statement for every dynamic element you wish to output works, but it's still a bit tedious to type "echo" every time. During the development of PHP, some PHP programmers were migrating to PHP from ASP (Microsoft's scripting environment known as Active Server Pages, which is somewhat similar to PHP). These programmers were used to ASP tags, which come in two varieties: the regular ASP tags, which, like PHP tags, separate ASP code from static output; and the ASP equals tag. The ASP equals tag added an equals sign to the opening ASP tag (hence the name "equals tag") and eliminated the need for an explicit command to print output.

PHP has a second short tag that was modeled after ASP's equals tag. Like ASP's equals tag, it shortens the amount of code it takes to output a value and eliminates the need for the echo statement by appending an equals sign to PHP's short tag.

NOTE

Remember that short tags must be enabled in PHP's configuration file for them to work. The short tag and the short equals tag are collectively classified as PHP's "short tags." If you experience problems or short tags don't work as expected, consult the configuration section of the PHP manual.

Take a look at the following excerpt, which puts PHP's short equals tag to use:

<?= "This is outputted automagically by the short equals tag!" ?>

Where the letters "php" would appear in a regular PHP tag, there is now an equals sign.

CAUTION

The equals sign must be directly attached to the tag—spaces separating the equals sign from the question mark are not allowed. Also, the short equals tag does not work with the regular PHP tag: Combining <?= with <?php to get <?php= will result in a generic parse error.

Now that you understand the basics of the short equals tag, let's take a look at its advantages. The short equals tag can significantly reduce the complexity of your code and increase its readability. Take a look at the following code segment, which doesn't use the short equals tag:

<?php
/* ch03ex06.php – demonstrates code using standard PHP tags with echo */

$title = "Example Title";
$text = "Here's some text!";

?>
<html>
<head><title><?php echo $title; ?></title></head>
<body><?php echo $text; ?></body>
</html>

Now compare it to the simpler version of the same code:

<?php
/* ch03ex07.php – demonstrates short equals tag */

$title = "Example Title";
$text = "Here's some text!";

?>
<html>
<head><title><?= $title ?></title></head>
<body><?= $text ?></body>
</html>

While both of these have the same output, the second one is quicker and easier to type. In fact, many developers prefer it to the tediousness of the first method.

CAUTION

Of these two methods, I will use the latter throughout this book to keep my code concise and as clear as possible. However, before adopting the short tags for use on any major project, you should ensure that your host will allow you to use short tags so you don't run into problems if your host has short tags disabled for some reason.

Here-doc Versus the Short Equals Tag

To summarize the differences between using here-doc or the short equals tag, here-doc can be handy in certain instances (like storing a long string to a variable), but it isn't usually a very good way to send output. For clarity, it's probably wiser to stick with the short equals tag or even regular PHP tags with an echo statement, if necessary. However, if you absolutely are stuck on using multiline strings to send output, here-doc is a better way to do it than double-quoted strings, stylistically.

So you can compare the two for yourself side-by-side, the following account information program has been provided using each method. The output is the same for both examples; a program like this would typically be used on an e-commerce or members-only site to tell the user important information about his account, such as his account number and the e-mail address he registered with.

Here's the here-doc version:

<?php
/* ch03ex08.php – displays account info using here-doc */

// Set up example account information
$user_name = "John Williams";
$user_email = "johnw@example.com";
$user_acctno = 1152;

// Display account info code
echo <<<END_HTML
<b>Name:</b> $user_name<br>
<b>E-Mail:</b> $user_email<br>
<b>Account Number:</b> $user_acctno<br>
END_HTML;

?>

And here's the short equals tag version of the same program:

<?php
/* ch03ex09.php – displays account info using equals tags */

// Set up example account information
$user_name = "John Williams";
$user_email = "johnw@example.com";
$user_acctno = 1152;

// Display account info code
?>
<b>Name:</b> <?= $user_name ?><br>
<b>E-Mail:</b> <?= $user_email ?><br>
<b>Account Number:</b> <?= $user_acctno ?><br>
<?php

// This space can be omitted, but is included to show that
// more code could be included here if desired.

?> 
  • + Share This
  • 🔖 Save To Your Account