PHP Echo

You will be using the PHP echo command over and over again, so you should become familiar with it. The good news is that it’s pretty easy to understand.

The echo command is simple: it instructs what to “echo” or display to the user. What is echoed is usually the end result of a string, but can also be a simple statement.

Echo A Simple Statement

An example of using the echo command to output a simple statement can look like:


echo "My favorite website is JWRmedia.com";

This bit of code would display:

My favorite website is JWRmedia.com

You are simply commanding the statement “My favorite website is JWRmedia.com” to be “echoed”, or outputted to the user.

This can also be combined with HTML:


echo "My favorite website is:
";
echo "JWRmedia.com";

This bit of code would display:

My favorite website is:
JWRmedia.com

Echo The End Result Of A String

You can also set a string value, then echo the result:

$favorite = "JWRmedia.com";

echo "My favorite website is:
";
echo "$favorite";

This bit of code would display:

My favorite website is:
JWRmedia.com

Echoing Results With Quotes

The one curve ball that the PHP echo command throws at you is the fact that you can’t echo direct quotation marks (“) without escaping them.

What this means is that you simple have to include a backslash (\) before each quotation mark.

Let’s use an example:


echo "My favorite website is JWRmedia.com";

The above bit of code will not work and will result in an error. Rather, we escape the quotation marks like so:


echo "My favorite website is JWRmedia.com";

Notice the backslash before each quotation mark.

It is also important to notice that each line ends with a semicolon (;). Not including the semicolon will result in an error, so be sure you include it at the end of each line! For more information, see PHP syntax.