PHP for Beginners: Using Echo and Print for Output
Published February 20, 2024 at 11:53 am

Getting Started with PHP: Basics of Echo and Print
If you are just stepping into the world of PHP, one of the first things you will learn is how to output data to the screen.
What are the primary ways to output text in PHP?
The primary ways to output text in PHP are using the echo
statement and the print
command.
Before diving into the intricacies of PHP output, make sure you have a server environment that supports PHP, like XAMPP or MAMP, and that you are running a version compatible with the code examples provided, typically PHP 5 or higher.
TLDR;
echo
and print
are both used to output data to the screen in PHP, with echo
being slightly faster and print
acting as an expression with a return value.
Understanding Echo in PHP
echo
is a language construct used to output one or more strings.
It is not a function, so you do not need to use parentheses with it.
echo
can take multiple parameters, though these are not commonly used.
Examples of Echo Usage
Here is a simple example of using echo
:
<?php echo "Hello, world!"; ?>
You can also separate strings with commas:
<?php echo "Hello", ", ", "world!"; ?>
Understanding Print in PHP
On the other hand, print
is considered a real function (though it behaves like a language construct) and can only output one string at a time.
It also always returns 1, so it can be used in expressions.
Examples of Print Usage
Here’s how you use print
to output text:
<?php print "Hello, world!"; ?>
Since print
returns a value, you can use it in expressions like this:
<?php if(print "Hello, world!") { echo " PHP is fun!"; } ?>
Pros and Cons of Echo and Print
Advantages of Using Echo
- Can output multiple strings.
- Slightly faster than
print
because it does not return a value. - Does not require parentheses, making it slightly more succinct.
Advantages of Using Print
- Returns a value (1), so it can be used in expressions.
- Behaves in a similar fashion to a function, which might be more intuitive for some developers.
Drawbacks of Using Echo
- Cannot be used in expressions as it does not return a value.
Drawbacks of Using Print
- Only capable of outputting one string at a time.
- Marginally slower than
echo
, as it always returns a value.
When to Use Echo Vs. Print
echo
is generally the go-to choice for output in PHP because it is slightly faster and does the job succinctly.
Use print
if you need the return value of 1 for some reason, like in an if statement.
Frequently Asked Questions
Can echo
and print
output more than just text?
Yes, echo
and print
can output text, HTML, and PHP variables.
Is there any case where print
is better than echo
?
print
may be better if you need a return value for an expression, but this use case is rare.
Are there any other ways to output data in PHP?
Yes, PHP also offers print_r()
for printing human-readable information about a variable and var_dump()
which outputs more detailed information.
Can I use HTML tags within the strings output by echo
and print
?
Absolutely, you can embed HTML directly like so:
<?php echo "<strong>Bold text</strong>"; ?>
Do I need to escape special characters in the strings used with echo
and print
?
Within the context of PHP strings, certain special characters like the double quote or backslash should be escaped with a backslash.
Delving Deeper: How to Display Complex Data with Echo and Print
Now that you understand the basics, let’s look into displaying complex data using echo
and print
.
For instance, to display the contents of an array, you could loop through it with a foreach
statement and use echo
to output each element.
Looping Through Arrays with Echo
To iterate over an array and print its values, use the following syntax:
<?php
$colors = array("red", "green", "blue");
foreach ($colors as $color) {
echo $color . "<br>";
}
?>
This will display each color on a new line because of the HTML line break element <br>
.
Handling HTML Content with Echo and Print
Both echo
and print
are capable of outputting HTML content, allowing PHP to generate dynamic web pages.
To include HTML tags within an echo or print statement, just ensure they are within the quoted string.
<?php echo '<div class="container">' . "Your content goes here." . '</div>'; ?>
The above snippet outputs a div element with a class attribute and some content inside it.
Utilizing Heredoc Syntax for Multiline Output
For long or complex string output, PHP offers the heredoc syntax, which is a way to declare a string that spans multiple lines.
Heredoc is particularly useful when you need to include a large block of HTML code.
<?php
echo <<<EOT
<div class="container">
<h1>Welcome to Our Website</h1>
<p>Enjoy your stay!</p>
</div>
EOT;
?>
This code will output the complete div element with its contained h1 and p tags just as you would write in an HTML file.
Generating Dynamic HTML with PHP Variables
PHP’s real strength comes into play when you start to use its dynamic abilities to output HTML content.
For example, you could use a variable in an echo
statement to customize a user’s greeting:
<?php
$user_name = "Spencer";
echo "<h2>Welcome, " . $user_name . "!</h2>";
?>
This snippet would output a personalized welcome message within an h2 tag.
Handling Special Characters in Echo and Print
Special characters like double quotes and backslashes inside a string need to be escaped using the backslash \
.
<?php echo "He said, \"Hello, world!\""; ?>
The backslashes before each double quote ensure they are treated as part of the string to be output and not as PHP string delimiters.
Escaping HTML Characters in Strings
When you’re outputting user-generated content, it’s important to escape HTML characters to prevent security vulnerabilities like cross-site scripting (XSS).
PHP has functions like htmlspecialchars()
to escape HTML entities.
<?php
$user_input = '<script>alert("Hacked!");</script>';
echo htmlspecialchars($user_input);
?>
The htmlspecialchars()
function converts special characters to HTML entities, preventing them from being interpreted as HTML or JavaScript code.
Frequently Asked Questions
How can I display variables within string outputs in PHP?
Variables can be included directly within double-quoted strings or concatenated using the dot operator.
What are the differences between single quotes and double quotes in PHP strings?
Single-quoted strings treat most things as literal text, while double-quoted strings interpret special characters and variables.
Can PHP output JavaScript code using echo or print?
Yes, PHP can be used to output JavaScript code, as it is ultimately rendered as HTML by the browser.
How do I output the content of an object in PHP?
You can use print_r()
for outputting the accessible properties of an object, or var_dump()
for including private and protected properties as well.
Is there a performance difference when outputting large amounts of HTML with echo vs. print?
The performance difference is negligible for most practical purposes. Echo might be marginally faster, but for large-scale output, other factors like network latency will be more significant.
Shop more on Amazon