PHP Tip, using heredoc

If you need to print out a large amount of text or HTML, consider using heredoc notation instead of numerous echo statements. For example, the following code:

echo “This is a test, and this is line 1”;
echo “This is a test, and this is line 2”;
echo “This is a test, and this is line 3”;
echo “This is a test, and this is line 4”;
echo “This is a test, and this is line 5”;

…could be replaced by:

echo <<<EOT
This is a test, and this is line 1
This is a test, and this is line 2
This is a test, and this is line 3
This is a test, and this is line 4
This is a test, and this is line 5
EOT;

You can also insert variables into a heredoc echo:

$username = ‘Foobar’;

echo <<<EOT
<p><font face=’Verdana, Arial’ size=’2′>Hello, $username!</font></p>
<p><font face=’Verdana, Arial’ size=’2′>Welcome to the Members’ Area.</p>
EOT;

Using this method to print out large amounts of text is also substantially faster than calling the echo or print statements over and over again. You can save both keystrokes (when coding) and processor time (when executing) by using heredoc notation.

Comments are closed.