echo and print
suggest changeecho and print are language constructs, not functions. This means that they don’t require parentheses around the argument like a function does (although one can always add parentheses around almost any PHP expression and thus echo("test") won’t do any harm either). They output the string representation of a value. An array becomes the string Array and raises a warning. An object is printed only if it has __toString(); otherwise PHP raises an error.
- Assign the string
Joelto the variable$name
$name = "Joel";
- Output the value of $name using
echo&print
echo $name; #> Joel
print $name; #> Joel
- Parentheses are not required, but can be used
echo($name); #> Joel
print($name); #> Joel
- Using multiple parameters (only
echo)
echo $name . "Smith"; #> JoelSmith
echo $name, " ", "Smith"; #> Joel Smith
print, unlikeecho, is an expression (it returns1), and thus can be used in more places:
print("hey") && print(" ") && print("you"); #> you11
- The above is equivalent to:
print ("hey" && (print (" " && print "you"))); #> you11
Shorthand notation for echo
When outside of PHP tags, a shorthand notation for echo is available by default, using <?= to begin output and ?> to end it. For example:
<p><?=$variable?></p>
<p><?= "This is also PHP" ?></p>
Note that there is no terminating ;. This works because the closing PHP tag acts as the terminator for the single statement. So, it is conventional to omit the semicolon in this shorthand notation.
Priority of print
print is a language construct with operator precedence. It sits below the assignment operators and above and, and it associates left to right. For example:
echo '1' . print '2' + 3; //output 511
Same example with brackets:
echo '1' . print ('2' + 3); //output 511
Differences between echo and print
In short, there are two main differences:
printonly takes one parameter, whileechocan have multiple parameters.printreturns a value, so can be used as an expression.