PHP ยท Chapter 4 of 44

PHP Echo & Print

echo and print are used to output data to the screen. They are very similar, but echo can take multiple, comma-separated parameters, while print can only take a single argument and always returns 1.

Both echo and print are language constructs, not real functions, so parentheses are optional. Because echo is marginally faster and more flexible, it is the more commonly used of the two.

Syntax
echo "text", $var;
print "text";

Using echo

echo can output strings, numbers, and variables, and can accept several comma-separated values in one call, printing them next to each other with no separator.

Using print

print behaves like echo but only accepts one argument and returns the integer 1, which means it can technically be used inside an expression.

Example 1 (php)
<?php
  echo "Hello", " ", "World!";
?>
Output
Hello World!

echo joins multiple comma-separated arguments with no extra spacing added automatically.

Example 2 (php)
<?php
  $age = 25;
  print "Age: " . $age;
?>
Output
Age: 25

print takes a single string, built here using the concatenation operator.

Key points

  • echo and print both output data to the page.
  • echo can accept multiple comma-separated arguments; print accepts only one.
  • Parentheses are optional for both echo and print.
  • print always returns the value 1.
๐Ÿ’ก Note: Most PHP developers prefer echo for everyday output because it is slightly faster and more flexible.

๐Ÿ“ Quick Quiz

1. Which can take multiple comma-separated arguments?

2. What does print always return?

3. Are parentheses required with echo?