PHP Reference ยท Language Constructs and Statements
PHP echo statement
Reference for PHP echo: output one or more strings, comma-separated arguments versus concatenation, short echo tags, and how it differs from print.
echo sends one or more values to the output. It is a language construct, not a function, so parentheses are optional and it has no return value. In a command-line script the output goes to the terminal; in a web request it becomes part of the response body.
Values that are not strings are converted to strings first: integers and floats become their decimal text, true becomes "1", false and null become the empty string. Arrays cannot be converted meaningfully (you get the word Array and a warning), so use print_r() or var_dump() for those.
echo "Hello", " ", "world", "\n"; echo 42, "\n";
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
echo expression [, expression ...]; <?= expression ?>
| Name | Description |
|---|---|
expression |
One or more values separated by commas. Each is converted to a string and written in order. |
Return value: none. echo cannot be used inside an expression.
Errors: an array argument produces a warning ("Array to string conversion"); an object without __toString() throws an Error.
Usage notes
- Commas versus dots.
echo $a, $b;outputs the values one by one;echo $a . $b;first builds a single string. Both look the same, but remember that.and+have different precedence when mixed with arithmetic (since PHP 8,+binds tighter than.). - Parentheses do not make it a function call.
echo("a"), ("b");works, butecho("a", "b");is a syntax error because("a", "b")is not an expression. - Short echo tag.
<?= $x ?>is equivalent to<?php echo $x; ?>and is always available, even whenshort_open_tagis off. It is the usual way to print values inside HTML templates. - Escape output for HTML. In a web page, pass untrusted values through
htmlspecialchars()before echoing them; see Escaping output. - Floats print with the
precisionsetting (14 significant digits by default forecho,-1for shortest round-trip invar_dumpandvar_export), soecho 0.1 + 0.2shows0.3. echoversusprint.printtakes one argument and returns1, so it can appear inside an expression.echois marginally lighter and accepts several arguments.- Output buffering. If
ob_start()is active,echowrites into the buffer instead of sending the text immediately. printf()andsprintf()are better when you need padding, rounding or fixed decimals.
Related
print,heredoc and nowdoc,exit and die- Lessons: echo and print, Strings