php
  1. php-echo-vs-print

PHP Echo vs Print

In PHP, echo and print are two of the most commonly used statements for displaying output to the browser. While they both serve the same purpose, there are some differences between them that are important to understand. In this article, we'll take a closer look at echo vs print in PHP.

Syntax

Echo

The syntax for the echo statement is straightforward:

echo expression;

Where expression can be any valid PHP expression.

Print

The syntax for the print statement is also straightforward:

print expression;

Where expression can be any valid PHP expression.

Example

Echo

Here's an example of using echo to display "Hello, World!" on the browser:

echo "Hello, World!";

Print

Here's an example of using print to display "Hello, World!" on the browser:

print "Hello, World!";

Output

Echo

The output of the echo statement is what you would expect; it simply displays the value of the expression to the browser window:

Hello, World!

Print

The output of the print statement is also the same; it displays the value of the expression to the browser window:

Hello, World!

Explanation

Echo

The echo statement is a language construct that outputs one or more strings. It is not actually a function, so you don't need to enclose the expression in parentheses. You can use echo with or without parentheses.

Print

The print statement is also a language construct that outputs one or more strings. However, unlike echo, print only accepts one argument and returns a value (1) upon successful execution. print is actually a function and requires parentheses.

Use

Echo

In PHP, echo is used to output text or HTML to the browser. It is commonly used to display data from a database, or to output dynamic content to the browser.

Print

print is less commonly used than echo, but it can be used to achieve the same effect. It is often used in situations where the return value of the function is important.

Important Points

  • Both echo and print are used to output text or HTML to the browser in PHP.
  • echo is not a function, while print is a function.
  • echo is more commonly used than print.

Summary

Both echo and print are commonly used to output text or HTML to the browser in PHP. The main difference between them is the fact that echo is not a function, while print is a function. In most cases, echo is the preferred choice because it is simpler to use and more commonly used in PHP.

Published on: