Skip to main content

How to Print Output in PHP with echo

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

echo is how a PHP script writes text: to the terminal for a command-line script, to the page for a web request. It prints exactly what you give it, with no spaces or new lines added, so you place those yourself.

Syntax​

Syntax
echo <expression>, <expression>, ...;
PartWhat it does
echoPrints one or more values. It's a language construct, so it needs no brackets.
<expression>, ...The values, separated by commas, printed one after another.
"\n"A new line, in a double-quoted string.

The PHP manual for echo: "Outputs one or more expressions, with no additional newlines or spaces." And: "echo is not a function but a language construct."

The Example​

The example prints a sentence, a label with a number, and one line built from two echo statements.

Prerequisites​

  • PHP for the command line. This guide uses PHP 8.6.0.

Step 1: Write the Code​

Create a file named main.php:

main.php, which echoes Hello from PHP, then Total: with 42, then No new line here, without a new line and then a new line. with one.

main.php
<?php

echo "Hello from PHP\n";
echo "Total: ", 42, "\n";
echo 'No new line here, ';
echo "then a new line.\n";

Step 2: Run It​

Terminal
php main.php
Output
Hello from PHP
Total: 42
No new line here, then a new line.

A zsh terminal where php main.php prints Hello from PHP, Total: 42 and No new line here, then a new line.

  • "Total: ", 42, "\n" printed three values one after another, with no spaces added between them.
  • The third echo ended without "\n", so the fourth continued on the same line.

The command is the same in zsh, bash and PowerShell.

Common Mistakes​

MistakeWhat happensDo this instead
Writing echo("a", "b") with brackets around several valuesParse error: syntax error, unexpected token ","Leave out the brackets: echo "a", "b";
Writing '\n' in single quotesIt prints a backslash and an n, not a new lineUse "\n" in double quotes
Echoing an arrayWarning: Array to string conversion, then the word ArrayUse print_r or var_dump for arrays

Troubleshooting​

SymptomLikely causeFix
Output runs together on one lineNo "\n" at the endAdd "\n"
\n appears literallyThe string is in single quotesSwitch to double quotes

FAQ​

What's the difference between echo and print?​

print takes one value and returns 1, so it can be used inside an expression; echo takes several values and returns nothing. For printing, they work the same.

Where does echo output go?​

In a command-line script, to standard output; under a web server, into the page sent to the browser.

Conclusion​

echo prints its values exactly as given, separated by nothing and followed by nothing. Separate several values with commas and end lines with "\n".

Additional Resources​

  • echo, in the PHP manual.