Login | Contact Us | Site Map | Resources

PHP Basics

Home > PHP Tutorial > The Echo Statement

The Echo Statement

PHP gives two options to choose between in order to output text to the browser. Although the two options are similar, "echo" is used far more than "print" because it is generally faster, shorter to type, and sounds cool! For the examples in this tutorial we will be using echo exclusively, so let's learn all about it.

<?php
  $numbers = 123;
  echo "Why did the lizard go on a diet?";
  echo 'It weighed too much for its scales!';
  echo $numbers;
?>

Echo accepts both variables and strings (in single or double quotes). Variables can be "echoed" by themselves, or from inside of a double-quoted string, but putting variable names inside a single-quoted string will only output the variable name. For example:

<?php
  $numbers = 123;
  echo "There are only 10 numbers. These numbers are: $numbers";
  echo 'There are only 10 numbers. These numbers are: $numbers';
?>

The example above will result in:

There are only 10 numbers. These numbers are: 123
There are only 10 numbers. These numbers are: $numbers

HTML elements can be echoed as part of a string or variable, but they will be interpreted by the browser instead of being displayed as part of the string or variable. This brings up an interesting point, because when double quotes are used to begin and end a string, using double quotes inside of the string will cause errors. The same applies to single quotes. The following examples will cause errors:

<?php
  echo "<p style="color: green;"></p>";
  echo 'What's this? An error message?';
?>

There are two ways to fix this problem (besides the obvious "don't use quotes inside your string"). One way is to use only double quotes inside of single quotes, and to use only single quotes inside of double quotes. The better way is to "escape" each quote that would create a problem.. The escape character is a backslash \. The following examples will not cause errors:

<?php
  echo '<p style="color: green;"></p>';
  echo "<p style=\"color: green;\"></p>";
  echo "What's this? No error message?";
  echo 'What\'s this? No error message?';
?>

These rules, since they apply to strings, work the same with variables as they do with the echo statement. On the next page we will learn more about these suspicious stringy thingys.