Skip to main content

PHP Echo and Print Statements

PHP is a widely-used open source scripting language that is especially suited for web development. One of the most common tasks you'll perform in PHP is outputting data to the browser. PHP provides two basic ways to get output: echo and print.

While they are very similar, there are slight differences, and we'll explore both in this article.

Echo

echo is a language construct in PHP, not a function, so you can use it without parentheses. It can take multiple parameters, unlike print.

Here's a simple example:

<?php
echo "Hello, world!";
?>

In this script, "Hello, world!" is a string. Strings in PHP are set of characters wrapped in either single quotes (' ') or double quotes (" ").

You can also use echo to output variables. Here's an example:

<?php
$text = "Hello, world!";
echo $text;
?>

In this script, we first declare a variable named $text and assign it the value "Hello, world!". Then, we use echo to output the value of $text.

Print

print is also a language construct in PHP, not a function, so you can use it without parentheses. However, it can only take one parameter, unlike echo.

Here's a simple example:

<?php
print "Hello, world!";
?>

You can also use print to output variables:

<?php
$text = "Hello, world!";
print $text;
?>

Differences between Echo and Print

While echo and print are similar, there are a few key differences:

  1. echo can take multiple parameters, while print can take one.
  2. echo is slightly faster than print.

Here's an example of echo with multiple parameters:

<?php
echo "Hello, ", "world!", " I'm learning PHP!";
?>

To summarize, both echo and print can be used to output data in PHP. While they are similar, echo is a bit faster and can take multiple parameters.

Remember, PHP scripts start with <?php and end with ?>. Anything outside these tags is ignored by PHP and outputted directly to the browser. This can be handy for mixing PHP with HTML.

So, that about wraps it up for the basics of echo and print in PHP. Happy coding!

Remember, practice makes perfect. Try writing some scripts of your own to get a feel for using echo and print.