Skip to Content

PHP echo vs. print Statements

PHP has two ways to display output to the screen: echo and print. Both statements are extremely flexible and allow you to work with many data types, including strings, arrays, objects, and more.

The main difference between the two is the echo command does not provide a return value, making it marginally faster than print.

Usage

Since both echo and print are statements rather than functions, you can utilize each statement with or without parenthesis. For example, these four statements will output the exact same result:

echo 'Hello World!';
echo ("Hello World!");
print 'Hello World!'
print ("Hello World!");

// Hello World!

Multiline Strings

Each statement is not limited to use on a single line of code. You can spread your string across multiple lines as needed:

echo '
Here is the first line.
Here is the second line.
';

Escaping Single Quotes

If you're outputting text using single quotes but have a word with an apostrophe, you'll need to escape the apostrophe with a backslash \ character to prevent errors:

echo 'I didn\'t know this would work!';

Join Strings Example

You can join two strings together into a single string:

$str1 = "Hello World!";
$str2 = "Have a nice day!";

echo $str1 . " " . $str2;
// Hello World! Have a nice day!

HTML Example

Another great thing about each statement is you can output a variety of strings, including HTML:

echo '
<h2>Hello World!</h2>
<p>Have a nice day!</p>
';

Array Example

Array values can be added to a string using the following example:

$array = ["apples", "oranges"];

<code>
echo 'My two favorite fruits are ' . $array[0] . ' and ' $array[1];

Object Example

Similarly, you can add object values to a string and output accordingly:

$array = [
"fruit" => "orange"
];

echo 'If I had to pick one fruit, it would be an ' . $array["fruit"];

Conclusion

As you can see, the echo and print methods are both flexible, allowing you to easily output data to the screen and work with multiple data types.

Posted by: Josh Rowe
Created: August 28, 2022

Comments

There are no comments yet. Start the conversation!

Add A Comment

Comment Etiquette: Wrap code in a <code> and </code>. Please keep comments on-topic, do not post spam, keep the conversation constructive, and be nice to each other.