// Little known PHP features: calling echo with multiple parameters

First of all, many PHP newbies do not even know that echo is not a function but a language construct. This means, the following two lines of code do the same:

  echo "Hello world\n"; //because echo is NO function, brackets are not needed.
  echo("Hello world\n");

IMHO, you should use the first variant without brackets to signalize that echo is not a function1).

But even experienced developers do not know the possibility to pass more than one parameter - there is no need to concatenate strings with a dot (which may be useful in some situations). The following code does the same three times:

  $str1 = "one";
  $str2 = "two";
  $str3 = "three\n\n";
 
  //newbie style, most overhead because echo is called more often than needed
  echo $str1;
  echo $str2;
  echo $str3;
 
  //common style with concatenated string (on my machines with PHP 5.2,
  //64bit *ix, this is the fastest)
  echo $str1.$str2.$str3;
 
  //little known: pass more than one parameter (on my machines with PHP <5.1,
  //this is the fastest)
  echo $str1, $str2, $str3;

My personal experience/small note about the performance: the more variables are involved + the bigger their data is, the slower is a concatenated string in comparison to passing the vars as parameter. But the difference is getting really small on PHP >=5.2. Additionally, echo is really fast, no matter if you use concatenation or commas. Just prevent unneeded echo calls and everything is fine. :-)

1)
BTW: same with include[_once] and require[_once]

Leave a comment…




  • E-Mail address will not be published.
  • Formatting:
    //italic//  __underlined__
    **bold**  ''preformatted''
  • Links:
    [[http://example.com]]
    [[http://example.com|Link Text]]
  • Quotation:
    > This is a quote. Don't forget the space in front of the text: "> "
  • Code:
    <code>This is unspecific source code</code>
    <code [lang]>This is specifc [lang] code</code>
    <code php><?php echo 'example'; ?></code>
    Available: html, css, javascript, bash, cpp, …
  • Lists:
    Indent your text by two spaces and use a * for
    each unordered list item or a - for ordered ones.
I'm no native speaker (English)
Please let me know if you find any errors (I want to improve my English skills). Thank you!
QR Code: URL of current page
QR Code: URL of current page 2010:05:19:php-echo-works-with-more-than-one-parameter (generated for current page)