PHP Function Reference

PHP print() Function



The PHP print() function outputs an expression. The print() function is not actually a function but a language construct. Its argument is the expression following the print keyword, and is not required to use parentheses with it.

The major differences to echo are that print only accepts a single argument and always returns 1.

Syntax

print(expression)

Parameters

expression Required. Specify the expression to be sent to the output. Non-string values will be coerced to strings, even when the strict_types directive is enabled.

Return Value

Returns 1, always.

Example:

The example below illustrates on print() function.

<?php
//print do not require parenthesis
print "print does not require parentheses.\n";
print ("Although it can be used with parentheses.\n");

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

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

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

The output of the above code will be:

print does not require parentheses.
Although it can be used with parentheses.
print do not add newlineOR space
This string 
spans multiple 
lines.
This string also
spans multiple 
lines.

Example:

Consider one more example to see other properties of print() function.

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

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

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

print "\n";
//print has a return value 1, it can be used 
//in expressions - outputs "hello world"
if(print "Hello") {
  echo " World";
}

print "\n";
if(!print "Hello") {
  echo " World";
} else {
  echo " John";	
}
?>

The output of the above code will be:

This is an example
red and green and blue
9
Hello World
Hello John

❮ PHP String Reference