Home » Programming » PHP » Php Echo

How to Use the PHP echo Statement, With Examples

This quick tutorial will show you how to use the PHP echo statement to print/display information on screen.

A computer program isn’t much good if it doesn’t display some output to the user. The echo statement prints a simple string of text in PHP – usually to the web browser.

Syntax

echo is a simple statement with a simple purpose – and it has simple syntax:

echo expressions

Note that:

  • expressions should be one or more strings containing the text or characters you want to display on screen
    • If more than one expression is supplied, they should be separated by a comma
  • echo does not return a value
    • It is a command which solely prints information to the screen
    • There is no return value that could be assigned to a variable
  • Non-string expressions will be evaluated and coerced into a string for display
  • No newlines or spaces are added by echo – the text is output exactly as is

echo Examples

Here are some examples of the echo command in action:

// Output "Hello" to the screen
echo "Hello";

// Output multiple strings to the screen - note the spaces are added as echo will not add them itself
echo "Hello, ", "it ", "is ", "a ", "nice ", "day.";

// Output "foobar" to the screen - note that echo doesn't add newlines so the output of both echo statements will appear on the same line
echo "foo";
echo "bar";

// Echo multi-line text - newlines included within the expression is kept
echo "Line 1
Line 2";

// Any expression which produces a string can be used with echo
// Below, an array is joined with the implode function and output using echo
$colours = ['red', 'green', 'blue'];
echo implode(" and ", $colours);

// Non-string expressions will be evaluated and then coerced into a string
// The below statement will print "15" to the screen
echo 3 * 5;

For more examples and information, check out the official PHP documentation for the echo statement:

https://www.php.net/manual/en/function.echo.php

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment