★ wanayoo — archive 1999 http://fr.php.net/manual/ru/function.echo.phpNouvelle recherche | Portail wanayoo
PHP  
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | my php.net 
search for in the  
<cryptexplode>
view the version of this page
Last updated: Sun, 20 Feb 2005

echo

(PHP 3, PHP 4, PHP 5 )

echo -- Выводит одну или более строк

Описание

void echo ( string arg1 [, string argn...])

Выводит все аргументы.

На самом деле echo() - это не функция, а конструкция языка, поэтому заключать аргументы в скобки не обязательно, даже при использовании нескольких аргументов.

Пример 1. Примеры использования echo()

<?php
echo "Привет мир!";

echo
"Это занимет
несколько строк. Переводы строки тоже
выводятся"
;

echo
"Это занимет\nнесколько строк. Переводы строки тоже\nвыводятся";

echo
"Экранирование символов делается \"Так\".";

// с echo можно использовать переменные ...
$foo = "foobar";
$bar = "barbaz";

echo
"foo - это $foo"; // foo - это foobar

// ... и массивы
$bar = array("value" => "foo");

echo
"это {$bar['value']} !"; // это foo !

// При использовании одиночных кавычек выводится
// имя переменной,а не значение
echo 'foo - это $foo'; // foo - это $foo

// можно вывести просто значения переменных
echo $foo;          // foobar
echo $foo,$bar;    // foobarbarbaz

// Некоторые предпочитают передачу нескольких аргументов
// вместо конкатенации
echo 'Эта ', 'строка ', 'была ', 'создана ', 'несколькими параметрами.', chr(10);
echo
'Эта ' . 'строка ' . 'была ' . 'создана ' . 'с помощью конкатенации.' . "\n";

echo <<<END
Здесь используется синтаксис "here document" для вывода
нескольких строк с подстановкой переменных $variable.
Заметьте,что закрывающий идентификатор должен
располагаться в отдельной строке. никаких пробелов!
END;
// Следующая строка неверна, так как echo не является функцией
($some_var) ? echo 'true' : echo 'false';

// Но это можно записать по другому
($some_var) ? print('true'): print('false'); // print является функцией
echo $some_var ? 'true': 'false'; // echo вынесен за пределы выражения
?>

echo() имеет также краткую форму, представляющую собой знак равенства, следующий непосредственно за открывающим тэгом. Этот сокращенный синтаксис допустим только когда директива конфигурации short_open_tag включена.

I have <?=$foo?> foo.

Различия между print() и echo() рассматриваются в этой статье: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Замечание: Поскольку это языковая конструкция, а не функция, она не может вызываться при помощи переменных функций

См. также описания функций print(), printf(), и flush().



add a note add a note User Contributed Notes
echo
19-Feb-2005 12:01
essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....essa merda e uma bosta.....
Truffy
15-Jan-2005 10:02
You can use braces around variables as well as array items. This is useful to help recognition of your variables in your code, but most useful where the variable iteslf cannot be separated with spaces from the preceding/following code, for exmple in a file path:

If a path is assigned the variable $path, then this code will not work:

echo "$pathindex.php";

whereas this will

echo "{$path}index.php";
dannydannydanny at tranceaddict dot net
13-Apr-2004 06:19
Well, in regards to the usage of PRINT vs ECHO - I've benchmarked them.

http://dynacker.dotgeek.org/printvsecho/

You'll find that in most cases, echo is faster than print.
zombie)at(localm)dot(org)
25-Jan-2003 08:26
[Ed. Note: During normal execution, the buffer (where echo's arguments go) is not flushed (sent) after each write to the buffer. To do that you'd need to use the flush() function, and even that may not cause the data to be sent, depending on your web server.]

Echo is an i/o process and i/o processes are typically time consuming. For the longest time i have been outputting content by echoing as i get the data to output. Therefore i might have hundreds of echoes in my document. Recently, i have switched to concatenating all my string output together and then just doing one echo at the end. This organizes the code more, and i do believe cuts down on a bit of time. Likewise, i benchmark all my pages and echo seems to influence this as well. At the top of the page i get the micro time, and at the end i figure out how long the page took to process. With the old method of "echo as you go" the processing time seemed to be dependent on the user's net connection as well as the servers processing speed. This was probably due to how echo works and the sending of packets of info back and forth to the user. One an one script i was getting .0004 secs on a cable modem, and a friend of mine in on dialup was getting .2 secs. Finally, to test that echo is slow; I built strings of XML and XSLT and used the PHP sablotron functions to do a transformation and return a new string. I then echoed the string. Before the echo, the process time was around .025 seconds and .4 after the echo. So if you are big into getting the actual processing time of your scripts, don't include echoes since they seem to be user dependent. Note that this is just my experience and it could be a fluke.
zan at stargeek dot com
17-Jan-2003 09:18
even tho its not "recomended" or "suggested" here's a great example of an extremely simple and flexible template system that uses short echo tag syntax as placeholders http://www.stargeek.com/scripts.php?script=10&cat=display
russ-phpnet at x23 dot com
18-May-2002 02:46
Regarding the benchmarking code by asmo@mail.utexas.edu above:  I found the time savings are only evident when using a large number of arguments. 

On my server the break-even point is about 50.  With less than 50 arguments, his code is actually faster at concatenation.

With 5 args, I get: Concats took 8.9049339294434E-05 seconds Params took 0.00013697147369385

Percentage-wise, it appears to be 50% slower to use parameters than concatenation with a low number of arguments.
asmo at mail dot utexas dot edu
16-May-2002 05:29
When possible, it is faster to pass multiple parameters to echo versus passing one parameter which is many concatinations.  Below is a script which will preform a quick benchmark for you to see:

<?php
function getmicrotime()
{
   list(
$usec, $sec) = explode(" ",microtime());
   return ((float)
$usec + (float)$sec);
}

$args=array();
for(
$i=0;$i<10000;$i++)
      
$args[]="'line to output number $i\n'";
$concatEcho="echo ".implode("\n.",$args).";";
$paramEcho="echo ".implode("\n,",$args).";";
unset(
$args);
$startParam=getmicrotime();
eval(
$paramEcho);
$endParam=getmicrotime();
$startConcat=getmicrotime();
eval(
$concatEcho);
$endConcat=getmicrotime();
$concatTime=$endConcat-$startConcat;
$paramTime=$endParam-$startParam;
print
"\nConcats took $concatTime seconds\nParams took $paramTime\n";
?>

The results I got when running the script above were 6.047 seconds for concatinations and  1.781 seconds for parameter passing.  This was just executing the script via command line, having the output dumped to a console.  The performace increase is even greater when using a script on a webpage with output buffering.

<cryptexplode>
 Last updated: Sun, 20 Feb 2005
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This mirror generously provided by: nexen.net
Last updated: Mon Feb 21 05:12:00 2005 CET