By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Echo in PHP

The practice of echoing data in PHP is simple enough – or is it? This Tutorial deals with a couple of complex problems.

Edited: 2012-11-17 13:33

Your typical echo in php is pretty straight forward, either making use of single quotes or double quotes, but there are situations where neither can work. What if the HTML you where trying to output had both single quotes and double quotes in it?

Echo is not really a function like some sites claim it to be – there are things you can do with functions that you can't with echo. For example, echo does not require the use of parentheses.

  echo 'This is line 1
This is line 2
This is line 3';

In php echo is generally easy to use. You choose to use double quotes if your string either contains variables, or special character codes – such as \n (representing a line break in PHP.) – but what if your string contained both single quotes and double quotes?

Dealing with quotes in echo

The easiest way to get around double quotes used in the HTML, is by far to surround the echoed string with single quotes – this is however not always possible. Maybe you want to keep the ability to use variables and special codes in your string, or maybe you have both single and double quotes in your HTML.

Escaping the type of quotes that you are using for echo can solve the problem, making it possible to choose whatever you prefer to use. Escaping characters is done using the backslash, like demonstrated in the below example script:

  echo "You can escape the double quotes using the \"\\\" backslash character.";

Echo in php with here document syntax

The final method to get around the quotation problem is to use the here document syntax, demonstrated in the below example:

This syntax also allows you to use variables inside of your string. Just be careful not to indent the closing end identifier with spaces or tabs – the identifier can only consist of alphanumeric characters and underscores, and it can not begin with a digit character.

This massive string with line breaks, html, and all kinds of stuff, also contains both single "'" and double """ quotes.
This is written on line 2, have all the fun you want with it!