PHP Function Reference

PHP echo() Function



The PHP echo() function outputs one or more expressions, with no additional newlines or spaces. The echo() function is not actually a function but a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas, and is not required to use parentheses with it.

The major differences to print are that echo accepts multiple arguments and doesn't have a return value.

echo also has a shortcut syntax. This syntax is available even with the short_open_tag configuration setting disabled.

Note: Surrounding a single argument to echo with parentheses will not raise a syntax error, as the parentheses are actually part of the expression to be sent to the output, not part of the echo syntax itself. However, surrounding multiple arguments to echo with parentheses will generate a parse error.

Syntax

echo(expression)

Parameters

expression Required. Specify one or more string expressions to be sent to the output, separated by commas. Non-string values will be coerced to strings, even when the strict_types directive is enabled.

Return Value

No value is returned.

Example:

The example below illustrates on echo() function.

<?php
//echo do not require parenthesis
echo "echo does not require parentheses.\n";

//echo do not add newline or space
echo "echo do not add newline";
echo "OR space";

echo "\n";
//it prints multiple lines
echo "This string 
spans multiple 
lines.";

echo "\n";
//another way of printing multiple lines
echo "This string also \nspans multiple \nlines.";
?>

The output of the above code will be:

echo does not require parentheses.
echo do not add newlineOR space
This string 
spans multiple 
lines.
This string also 
spans multiple 
lines.

Example:

Consider the example below to see other properties of echo() function.

<?php
//echo can take any expression 
//that produces a string
$x = "example";
echo "This is an $x"; 

echo "\n";
//can take a function which returns string
$colors = ["red", "green", "blue"];
echo implode(" and ", $colors); 

echo "\n";
//non-string expressions are coerced to string
//even if declare(strict_types=1) is used
print (1 + 2) * 3;

echo "\n";
//multiple arguments can be passed separated by comma 
//which is equivalent to arguments concatenated 
//together and passed as a single argument
echo 'This ', 'string ', 'is ', 'made ', 
     'with multiple parameters.', "\n";
echo 'This ' . 'string ' . 'is ' . 'made ' 
     . 'with concatenation.' . "\n";
?>

The output of the above code will be:

This is an example
red and green and blue
9
This string is made with multiple parameters.
This string is made with concatenation.

Example:

Consider one more example to see the shortcut syntax of this function.

<?php
$color = "blue";
?>

<!-- shortcut syntax of echo -->
<p>Sky is <?=$color?>.</p>

The output of the above code will be:

Sky is blue.

❮ PHP String Reference

5