print
(PHP 4, PHP 5, PHP 7, PHP 8)
print — Output a string
Description
print is not a function but a language construct.
Its argument is the expression following the print keyword,
and is not delimited by parentheses.
The major differences to echo are that
print only accepts a single argument and always returns
1.
Parameters
expression
-
The expression to be output. Non-string values will be coerced to strings,
even when the
strict_types directive is enabled.
Return Values
Returns 1, always.
Examples
Example #1 print examples
<?php
print "print does not require parentheses.";
print PHP_EOL;
// No newline or space is added; the below outputs "helloworld" all on one line
print "hello";
print "world";
print PHP_EOL;
print "This string spans
multiple lines. The newlines will be
output as well";
print PHP_EOL;
print "This string spans\nmultiple lines. The newlines will be\noutput as well.";
print PHP_EOL;
// The argument can be any expression which produces a string
$foo = "example";
print "foo is $foo"; // foo is example
print PHP_EOL;
$fruits = ["lemon", "orange", "banana"];
print implode(" and ", $fruits); // lemon and orange and banana
print PHP_EOL;
// Non-string expressions are coerced to string, even if declare(strict_types=1) is used
print 6 * 7; // 42
print PHP_EOL;
// Because print has a return value, it can be used in expressions
// The following outputs "hello world"
if ( print "hello" ) {
echo " world";
}
print PHP_EOL;
// The following outputs "true"
( 1 === 1 ) ? print 'true' : print 'false';
print PHP_EOL;
?>
Notes
Note:
Using with parentheses
Surrounding the argument to print with parentheses will not
raise a syntax error, and produces syntax which looks like a normal
function call. However, this can be misleading, because the parentheses are actually
part of the expression being output, not part of the print
syntax itself.
When using print in a larger expression, placing both the
keyword and its argument in parentheses may be necessary to give the intended
result:
Note:
Because this is a
language construct and not a function, it cannot be called using
variable functions,
or named arguments.