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.
echo is a simple statement with a simple purpose – and it has simple syntax:
- 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
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: