search for in the  
<cryptexplode>
Last updated: Thu, 19 May 2005

echo

(PHP 3, PHP 4, PHP 5 )

echo -- Output one or more strings

Description

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

Outputs all parameters.

echo() is not actually a function (it is a language construct) so you are not required to use parentheses with it. In fact, if you want to pass more than one parameter to echo, you must not enclose the parameters within parentheses.

Example 1. echo() examples

<?php
echo "Hello World";

echo
"This spans
multiple lines. The newlines will be
output as well"
;

echo
"This spans\nmultiple lines. The newlines will be\noutput as well.";

echo
"Escaping characters is done \"Like this\".";

// You can use variables inside of an echo statement
$foo = "foobar";
$bar = "barbaz";

echo
"foo is $foo"; // foo is foobar

// You can also use arrays
$bar = array("value" => "foo");

echo
"this is {$bar['value']} !"; // this is foo !

// Using single quotes will print the variable name, not the value
echo 'foo is $foo'; // foo is $foo

// If you are not using any other characters, you can just echo variables
echo $foo;          // foobar
echo $foo,$bar;    // foobarbarbaz

// Some people prefer passing multiple parameters to echo over concatenation.
echo 'This ', 'string ', 'was ', 'made ', 'with multiple parameters.', chr(10);
echo
'This ' . 'string ' . 'was ' . 'made ' . 'with concatenation.' . "\n";

echo <<<END
This uses the "here document" syntax to output
multiple lines with $variable interpolation. Note
that the here document terminator must appear on a
line with just a semicolon. no extra whitespace!
END;

// Because echo is not a function, following code is invalid.
($some_var) ? echo 'true' : echo 'false';

// However, the following examples will work:
($some_var) ? print('true'): print('false'); // print is a function
echo $some_var ? 'true': 'false'; // changing the statement around
?>

echo() also has a shortcut syntax, where you can immediately follow the opening tag with an equals sign. This short syntax only works with the short_open_tag configuration setting enabled.

I have <?=$foo?> foo.

For a short discussion about the differences between print() and echo(), see this FAQTs Knowledge Base Article: http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40

Note: Because this is a language construct and not a function, it cannot be called using variable functions

See also print(), printf(), and flush().



User Contributed Notes
echo
Jason Carlson - SiteSanity
16-May-2005 01:28
In response to Ryan's post with his echobig() function, using str_split wastes memory resources for what you are doing.

If all you want to do is echo smaller chunks of a large string, I found the following code to perform better and it will work in PHP versions 3+

<?php
function echobig($string, $bufferSize = 8192)
{
 
// suggest doing a test for Integer & positive bufferSize
 
for ($chars=strlen($string)-1,$start=0;$start <= $chars;$start += $bufferSize) {
   echo
substr($string,$start,$buffer_size);
  }
}
?>
renrutal at gmail dot com
28-Mar-2005 06:34
Note that:

<?php
echo "2 + 2 = " . 2+2; // This will print 4
echo "2 + 2 = " , 2+2; // This will print 2+2 = 4
?>

The commas will parse the result of the expressions correctly.
paul dot mateescu at zirkonmedia dot ro
27-Feb-2005 05:35
Hello,

If you want to use echo <<<ENDOFECHO (here document style) and you notice that the server does not seem to recognise this form (you get a blank page with no content at all), chances are your editor uses a wrong type of line break.

Fore instance, I use Dreamweaver for Macintosh. You should have the following preferences:

Dreamweaver >> Preferences >> Code Format >> Line break type

set to "CR LF (Windows)" or "LF (Unix)". Dreamweaver for Mac ships with "CR (Macintosh)" by default (at least the MX edition, don't know about any other editions), which confuses the PHP interpreter.

Best,

Paul Mateescu
ryan at wonko dot com
27-Feb-2005 03:56
Due to the way TCP/IP packets are buffered, using echo to send large strings to the client may cause a severe performance hit. Sometimes it can add as much as an entire second to the processing time of the script. This even happens when output buffering is used.

If you need to echo a large string, break it into smaller chunks first and then echo each chunk. The following function will do the trick in PHP5:

<?php
function echobig($string, $bufferSize = 8192)
{
  
$splitString = str_split($string, $bufferSize);

   foreach(
$splitString as $chunk)
       echo
$chunk;
}
?>
Truffy
15-Jan-2005 04: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 12: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 02: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 03: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
17-May-2002 08: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
15-May-2002 11: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: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 18:35:34 2005 EDT