PHP: Echo vs Print
![]()
The following is derived from my post on the (now defunct) hawkee.com forums.
This is a hot topic for those just getting into php. Understanding the difference between print() and echo can be challenging for those unfamiliar with the language.
In my opinion, it really depends what your trying to accomplish that will determine which you should use. Some things to consider:
- echo is marginally faster than print()
- print() is a function, which can be used in more complex operations.
- echo can handle multiple parameters.
echo is faster
As stated, echo is marginally faster than print() . If you’re wondering how much faster, take a look at this.
I’ve created two php snippets: echo.php and print.php
Then I made a snippet to time them both: test.php .
We execute our test.php and see our results.
So ultimately, we confirm that echo is only slightly faster than print() .
print() is a function
However, this doesn’t necessarily mean that echo is better than print() , because print() can do something that echo can’t — it can be placed in more complex operations since it's a function.
Within the above, if the variable $i is set this snippet will print true . Since print() is a function, it’s able to be used within this operation, where echo can not. In fact if you were to attempt to use echo within this statement, php will error in:
echo accepts multiple parameters
Finally, echo can handle multiple parameters but, I think that pretty much speaks for itself. Give the following a try:
So, as stated, it really just depends on what your trying to accomplish. Others may have a different opinion but this is mine and I’m entitled to it 😛
PHP echo and print Statements
With PHP, there are two basic ways to get output: echo and print .
In this tutorial we use echo or print in almost every example. So, this chapter contains a little more info about those two output statements.
PHP echo and print Statements
echo and print are more or less the same. They are both used to output data to the screen.
The differences are small: echo has no return value while print has a return value of 1 so it can be used in expressions. echo can take multiple parameters (although such usage is rare) while print can take one argument. echo is marginally faster than print .
The PHP echo Statement
The echo statement can be used with or without parentheses: echo or echo() .
Display Text
The following example shows how to output text with the echo command (notice that the text can contain HTML markup):
Example
Display Variables
The following example shows how to output text and variables with the echo statement:
Example
The PHP print Statement
The print statement can be used with or without parentheses: print or print() .
Display Text
The following example shows how to output text with the print command (notice that the text can contain HTML markup):
Example
Display Variables
The following example shows how to output text and variables with the print statement:
Php echo и print в чем разница
In this article, we will see what is echo & print statements in PHP, along with understanding their basic implementation through the examples. The echo is used to display the output of parameters that are passed to it. It displays the outputs of one or more strings separated by commas. The print accepts one argument at a time & cannot be used as a variable function in PHP. The print outputs only the strings.
Note: Both are language constructs in PHP programs that are more or less the same as both are used to output data on the browser screen. The print statement is an alternative to echo.
PHP echo statement: It is a language construct and never behaves like a function, hence no parenthesis is required. But the developer can use parenthesis if they want. The end of the echo statement is identified by the semi-colon (‘;’). It output one or more strings. We can use ‘echo‘ to output strings, numbers, variables, values, and results of expressions. Below is some usage of echo statements in PHP:
Displaying Strings: We can simply use the keyword echo followed by the string to be displayed within quotes. The below example shows how to display strings with PHP.
Output:
Displaying Strings as multiple arguments: We can pass multiple string arguments to the echo statement instead of a single string argument, separating them by comma (‘,’) operator. For example, if we have two strings i.e “Hello” and “World” then we can pass them as (“Hello”, “World”).
Output:
Displaying Variables: Displaying variables with echo statements is also as easy as displaying normal strings. The below example shows different ways to display variables with the help of a PHP echo statement.
Output:
The (.) operator in the above code can be used to concatenate two strings in PHP and the “\n” is used for a new line and is also known as line-break. We will learn about these in further articles.
PHP print statement: The PHP print statement is similar to the echo statement and can be used alternative to echo many times. It is also a language construct, so we may not use parenthesis i.e print or print().
The main difference between the print and echo statement is that echo does not behave like a function whereas print behaves like a function. The print statement can have only one argument at a time and thus can print a single string. Also, the print statement always returns a value of 1. Like an echo, the print statement can also be used to print strings and variables. Below are some examples of using print statements in PHP:
Displaying String of Text: We can display strings with the print statement in the same way we did with echo statements. The only difference is we cannot display multiple strings separated by comma(,) with a single print statement. The below example shows how to display strings with the help of a PHP print statement.
Эхо или печать?
Вопрос: «Что быстрее — echo или print?» не перестаёт будоражить умы тех, кто считает себя профессиональным программистом на PHP. Руководство пользователя осторожно упоминает об имеющемся различии, но отсылает к статье стороннего авторства; та, в свою очередь, утверждает, что echo быстрее, но не приводит доказательств; трудно найти объективное сравнение, и всё это придаёт проблеме некий мистический ореол, на что клюют многие и многие.
Так не будем же оставаться в стороне и постараемся раз и навсегда разгадать эту загадку!
Поведенческое различие echo и print заключается в том, что последний может вести себя как функция (всегда возвращающая единицу); вследствие этого print можно использовать в контексте, например, тернарного оператора, что иногда может быть весьма привлекательным. Echo как функцию использовать нельзя, зато она может принимать несколько аргументов через запятую, при этом их нельзя брать в скобки; тогда как у print ровно один аргумент, и он может быть как в скобках, так и без.
Впрочем, об этих различиях информация как раз имеется в том же мануале, мы же имеем своей целью сравнить производительность и, я не побоюсь этого слова, быстродействие этих двух языковых конструкций.
Для проведения испытаний я составил стенд, на котором 1000 раз выводятся 1000 строк (длиной 32 символа каждая); при этом используется один из пяти методов:
- print "$value<br />";
- echo "$value<br />";
- print $value . ‘<br />’;
- echo $value . ‘<br />’;
- echo $value, ‘<br />’;
Для каждого из методов испытания проводились 20 раз, при этом каждый раз засекалось время. Распределение результатов для всех методов оказалось нормальным, что позволяет брать среднюю величину как показатель быстродействия.
Были получены следующие величины:
- 1,727 с
- 1,727 с
- 1,462 с
- 1,428 с
- 1,321 с
Действительно, мы видим что print может оказаться немного медленнее echo (а может и не оказаться, что демонстрируют результаты по первым двум методам). В то же время использование echo с несколькими параметрами взамен конкатенации (и одинарными кавычками вместо двойных) даёт весьма ощутимый выигрыш в производительности.
Но постойте, на самом ли деле он такой ощутимый? Давайте подсчитаем. Разница между минимальным и максимальным временем составляет 406 мс на миллион операций. То есть, как сейчас модно говорить, 406 наносекунд на одну операцию.
Что это нам даёт в масштабах — ну, скажем, «ВКонтакте»? По данным LiveInternet, ежедневно на нём просматривается 500 млн. страниц.
Сколько раз для каждой страницы вызывается echo или print? Современные успешные сайты обязательно прибегают к сколько-нибудь высокому уровню абстракции логики от представления, используя шаблоны, MVC и другие страшные слова; в результате операция вывода вызывается один раз на страницу или, как максимум, один раз для каждого смыслового блока страницы. Предположим худший вариант и оценим количество таких блоков в 10 шт. на одну страницу.
Нетрудно подсчитать, что экономия серверного времени составит в лучшем случае до 200 секунд в день, или 0,23 %. Много это или мало? Решайте сами. Только сначала подумайте, не принесёт ли оптимизация одного SQL-запроса или кэширование одного файла в несколько раз больший прирост производительности.