Using echo in PHP

Using echo in PHPIn PHP, echo is a language construct which allows you to display text directly to your browser. It simply ‘echoes out’ content.

As with all PHP, echo is parsed server-side only, so you’ll have to upload your code to a server in order for it work.

<?php
 echo "Hello PHP people!"
 ?>

You should now be able to see the following within your browser:

Hello PHP people!

So whatever you put after the echo construct, within the double/single quotes should be the only items on screen. Let’s try the same again, but this time using two lines.

<?php
 echo "Hello PHP people!";
 echo 'Is this another line?';
 ?>

This should show as:

Hello PHP people!Is this another line?

Even though the echo was split onto two separate lines, the text for each echo is joined together. In the above example, I have mixed the use of single and double quotes. In this case, using either single or double quotes will not have any differing effects.

Let’s try it with a line break. We’ll have to add a little HTML to our echo:

<?php
 echo "Hello PHP people!<br>";
 echo 'Am I using echo?';
 ?>
Hello PHP people!
Am I using echo?

Why use PHP echo?

You can use echo to parse variable data:

<?php
$total = 5 + 5;
echo "5 plus 5 equals $total";
?>

Although this tutorial is not focusing on the use of ‘string’ variables, I think that the above string ‘$total’ is fairly self-explanatory. Try it out in your browser.

Echoing Single and double quotes

We have seen that single and double quotes can be echoed out without a problem, but why not stick to one or the other? What is the difference? Now that we have added a string to our code, the choice of using a single or double quote is an important consideration.

Example:

<?php
$total = 5 + 5;
echo "5 plus 5 equals $total<br>";
echo '5 plus 5 equals $total';
?>

Result:

5 plus 5 equals 10
5 plus 5 equals $total

Notes how the second echo using the single quote literally echoes-out the string name rather than it’s associated variable content.

What if you wish to do the following:

<?php
$Name = "Gold Finger";
echo "Then $Name said, "Hello Mr Bond".";
?>

The above won’t work. The presence of the double quote around the dialogue will cause the double quote around the echo to terminate. If you wish to echo out a double quote within a double quoted echo, then you will need to escape it first using a backslash ”. You can also do this with single quotes:

<?php
$Name = "Gold Finger";
echo "Then $Name said, "Hello Mr Bond".";
?>

Using echo to join statements

You can break apart your echo statements between single and double quotes. If you are echoing a string, you don’t need to use either:

Example:

<?php
$total = 5 + 5;
$Name = "James";
echo 'So then' . $Name . ", 5 plus 5 equals $total<br>" . 'Don't you agree? "No!", he replies!';
?>
So then James, 5 plus 5 equals 10
Don't you agree? "No!", he replies!

Leave a Reply

Your email address will not be published. Required fields are marked *