Page 2 of 3
The echo command is one of a number that send output to the browser and they all have their uses but you can send output to the browser without any commands at all. If you simply include some text in the PHP program that is outside of the <?php and ?> tags then it is simply sent to the browser unmodified. So you could have written the previous program as:
Hello PHP World
with no sign of a PHP command anywhere and no <?php ?> tags - you don't even need quotes around the text.
The rule is:
- Any text not enclosed in <?php ?> is simply passed to the output as if it was within an echo instruction.
This makes it possible to include blocks of HTML, or text that is part of the web page, that never change and isn't processed by PHP commands.
You can even interweave text and PHP as and when it is needed. So you can have some text, a block of PHP, some more text and then some more PHP and the result is sent to the output in the same order. For example:
echo 'PHP' ;
Notice that all of the text is on a single line even though it looks as if it should be on separate lines. The reason is that a web browser ignores any line breaks in the text that is sent to it. If you want to format text in a web page then you have to use HTML tags to do the job. In particular if you want a line break you need to use the tag <br/> . For example:
echo 'Hello <br/>';
echo 'PHP <br/>' ;
echo 'World <br/>';
which has line breaks after each word. Notice the two different ways that the <br/> tag has been inserted - just as part of the text of the page and within an echo instruction. The effect is the same however and the <br/> tag is sent to the output and hence to the client browser with the result:
You can see that the problem with this approach to building a PHP program is that it is very messy. You have PHP, HTML and plain text intermingled and this makes it very difficult to read. When if comes to programming the simpler things are the better because there is less likelihood that a bug will use the mess to hide.
There are ways to make the generation of a web page appear much simpler and more straightforward to follow but it involves some more advanced ideas. For the moment you need to keep in mind that the examples that follow might not be written in the best possible way for real use but in the best possible way to demonstrate some point or idea.
The key point to keep in mind is that the purpose of a PHP program is to generate a web page and the HTML, text or whatever can be embedded into the program or generated by echo or similar instructions.
Some programmers like to think of a PHP program as a web page that happens to have some PHP instructions embedded in it at various places. You might find this helpful but thinking about a PHP program as something that generates text and HTML to be sent to the browser is closer to reality.