<< PHP Comments | PHP Tutorials | PHP Strings >>

PHP Output - echo and print

PHP was made to handle data and then send it out. So why not learn how to actually do this? There are two ways to output data in PHP: echo and print. Some people say there is no difference between the two, but there is, and it can be found here. The 'echo' and 'print' methods are not actually PHP functions, they are language constructs (you basically don't need ( and ) ). In this tutorial I will be showing all the examples with echo and not print. The section directly below is using echo, but it can be replaced with print.

Outputting Data Using echo

Using PHP to output data is easy. You just need the echo followed by what it is outputting. For example:

<?php
$variable = 1;
echo 'String';
echo $variable;
echo '<i>Italic</i>';
?>

What the end user sees:

String1Italic

Yes! PHP can be used to output HTML, as I said at the start of this tutorial, they go together like ... well you know :P Anyway, you can output mostly any data type in PHP, because the PHP parser will automatically convert it to a string for you (that's why it's great).

Outputting Data Using a ... what? a hole?

As you can see from the title, you can also output data using a 'hole' (as I like to call it) in the PHP code. You see, PHP is magical, and can read PHP that is broken up into blocks. For example:

<?php
echo 'Hello<br />';
?>
<i>How are you?</i><br />
<?php
echo 'Cool';
?>

What the end user sees:

Hello
How are you?
Cool

Notice that there is a 'hole' in the PHP tags. This is useful if you want to output a lot of lines of HTML to the user. You can also put little PHP code snippets in there if you needed to:

<?php
echo 'Hello';
?>
<i>How are <?php echo 'you'; ?>?</i><br />
<?php echo 'Cool';
?>

What the end user sees:

Hello
How are you?
Cool

See? Exactly the same thing just a little more complicated.

Quotes and PHP

This part may be a little more complicated than before, but nevertheless important. PHP uses quotes to show that it is a string, so if you have something like this:

<?php
echo 'It's really simple';
?>

<

Will return an error because the parser thinks the string already ended after It. To avoid this, you have to use a backslash ( \ ) before the character. If that made no sense look at this example (it will work):

<?php
echo 'It\'s really simple';
?>

See? This is the same with double quotes (which I haven't shown you yet):

<?php
echo "He said \"Hello\"";
?>

What the end user sees:

He said "Hello"

But you could use single quotes ( ' ) inside double quotes ( " ) and vice versa:

<?php
echo "It's really simple<br />";
echo 'He said "Hello"';
?>

What the end user sees:

It's really simple
He said "Hello"

You don't have to worry about quotes inside 'holes' in the PHP blocks though. I will go into more detail on double quotes and single quotes in the string tutorial.

<< PHP Comments | PHP Tutorials | PHP Strings >>