Skip to main content.

Tuesday, August 31, 2004

When using the echo "function" to output a string which is combined of multiple parts, once could write:

echo 'foo' . htmlspecialvars($someVar) . 'bar'

The problem with this is that PHP will first concatenate the three strings (two concatenations) before using echo to dump it to the output. This means that two extra string objects will be created into memory.

The alternative is using comma's. It looks a little weird, but echo then behaves as a function that is taking multiple parameters and dumping all of them:

echo 'foo' , htmlspecialvars($someVar) , 'bar'

In this case, no concatenation is needed which means this code should be faster and more memory-efficient than the concatenating version.

I know the effect of this will be very limited, but I try to use this wherever I can.

Comments

Hmmmm! Yes, it looks weird because it is the first time I see it. :-)

Posted by moraes at Tuesday, August 31, 2004 17:31:08

I knew both could be used (that's one of the few differences between echo and print if i should believe my book about php ;-)) but, until now, always used the . I'll start using the , in the future :-)

Posted by TeRanEX at Tuesday, August 31, 2004 21:06:28

Little fix in ADMIN.php, line 4539 (Nucleus 3.1+CVS/1): echo '<h2>',_QMENU_PLUGINS,'</h2>';

with this concatenation, the constant will be translated properly.

Posted by moraes at Monday, September 06, 2004 06:17:49

@moraed: thanks. updated cvs

Posted by karma at Wednesday, September 08, 2004 18:51:00

Nice tip; never thought about that before. Thanks!

Posted by Jan! at Friday, September 17, 2004 01:05:18

It's also the first time I see this, very interesting.

Posted by Bart N. at Monday, January 03, 2005 00:37:10

Awesome! I hated dots anyway... nice post!

Posted by JesterXL at Wednesday, March 16, 2005 05:54:59

Nice. Dots or commas, I happy as long as my scripts are happy.

Posted by Matt at Wednesday, March 16, 2005 05:59:39

test

Posted by John at Thursday, May 19, 2005 17:13:10

Thanks for the tip!

Posted by Devin Hendricks at Monday, September 04, 2006 21:13:58

Great tip!

Posted by Pozycjonowanie at Saturday, November 18, 2006 05:10:08

thanks for u r help this blog is one of the nice bloge ever i seen.

once again thanks

Posted by shardul kulkarni at Wednesday, November 22, 2006 15:40:41

Add Comment

This item is closed, it's not possible to add new comments to it or to vote on it