Skip to main content

PHP echo and print Statements

PHP gives you two basic statements for producing output, echo and print, and they are nearly interchangeable. The differences are small. print returns a value of 1, which means you can use it inside an expression, while echo returns nothing. echo accepts several parameters (something you'll rarely see in practice), but print takes just one argument. echo also runs slightly faster.


The PHP echo Statement

Use echo to output one or more strings. Parentheses are optional, so both echo and echo() are correct.

Display text with echo

Output some text with echo. The strings can include HTML markup, as the heading and line break show here:

Prompt
Write a PHP script that uses echo to display a heading "PHP is Fun!" wrapped in an h2 tag, then echoes "Hello world!" on the next line, and then echoes "I'm about to learn PHP!" on the next line.
Output: PHP script

Display variables with echo

Besides plain text, echo can print the contents of variables, here a string, an integer and a decimal number:

Prompt
Write a PHP script that creates a variable $txt set to "Hello world!", a variable $x set to 5, and a variable $y set to 10.5. Use echo to display $txt on one line, then echo $x on the next line, then echo $y on the next line.
Output: PHP script

Display variables in a string with echo

Inside a double-quoted string, a variable is replaced by its value, so echo prints the text with $txt filled in:

Prompt
Write a PHP script that creates a variable $txt set to "PromptCookbook". Use echo with a double-quoted string to output "I love $txt!" so the variable value is interpolated.
Output: PHP script

The PHP print Statement

Use print to output a string; it gives back 1 every time. As with echo, parentheses are optional, so you can write print or print().

Display text with print

The same text output, now written with print. Again, the strings can carry HTML markup:

Prompt
Write a PHP script that uses print to display a heading "PHP is Fun!" wrapped in an h2 tag, then prints "Hello world!" on the next line, and then prints "I'm about to learn PHP!" on the next line.
Output: PHP script

Display variables with print

print handles variables just as well. Each value here goes out in its own statement:

Prompt
Write a PHP script that creates a variable $txt set to "Hello world!", a variable $x set to 5, and a variable $y set to 10.5. Use print to display $txt on one line, then print $x on the next line, then print $y on the next line.
Output: PHP script

Display variables in a string with print

Double-quoted strings work the same way with print, so $txt is swapped for its value:

Prompt
Write a PHP script that creates a variable $txt set to "PromptCookbook". Use print with a double-quoted string to output "I love $txt!" so the variable value is interpolated.
Output: PHP script