Echo: Best Practice Quesiton

I was reading through the PHP & MySQL Coding Tips topic (http://www.sitepoint.com/forums/showthread.php?t=456441) and this particular tip caught my question:

I much prefer the following:

PHP Code:

$something = 'this
and this
and this
and this';

Why? Because in the first two examples PHP is having to allocate memory for multiple strings and then go through the (relatively) expensive process of “sticking” them together again. If you just declare a string over multiple lines you are avoiding that overhead. You have to be careful to make code readable if you do this but I’ve never had any problems with it.

Does this mean that multi-line echo statements are are better written as:

echo 'something
something
something
something';

as oppsed to:

echo 'something';
echo 'something';
echo 'something';
echo 'something';

Just curious for thoughts and opinions.

I think this is better.

echo 'this
this
this';

I didn’t know echo statements were stored in memory, I thought only variables were.

It’s easier to write a multiple line echo in my opinion.

You could also concenate the string if you wanted but doesn’t seem as useful :stuck_out_tongue:

echo 'this' .
'this' .
'this';

Won’t make any significant difference.

There is a difference, as one will have newlines within it while the other will be run together.

I used to prefer heredoc syntax:


echo <<< EOT
    this
    this
    this

EOT;

but there are concerns with code indentation, so am now leaning more towards:


echo 'this'
    . ' this'
    . ' this';

Especially when it comes to SQL statements.

The following is an example of some code using PEAR’s MDB2 library:


return $db->extended->getAll(
    'SELECT Id, Type, Purchased, Remaining'
    . ' FROM AlertsPackage'
    . ' WHERE'
        . ' UserId = ?'
        . ' AND Enabled = 1'
        . ' AND Remaining > 0'
        . ' AND adddate(Purchased, INTERVAL 1 YEAR) > now()'
    . ' ORDER BY Purchased ASC'
, NULL
, array($userId)
, array('integer')
, MDB2_FETCHMODE_ASSOC
);

I was referring to performance, which was the question asked.

If you have a lot of stuff to echo, then why are you echoing it though. Just close php and output html.

When it comes to strings for sql I prefer:

$sql="
    SELECT
        *
    FROM
        a_table
    WHERE
        this = '$that'
":

Normally for echos i do


echo 'The start of the line here...';
echo '...and the end of it here';

But i’ve started moving towards doing


echo 'The start of the line here...
...and the end of it here';

The only downside I find with the later is that it confuses the syntax highlighter of Emerald Editor.

Some text editors have trouble when it comes to multi-line strings.

Do we know if these reported issues have less prevalence these days?

Multi-Line Strings and Text Editors

Not had that problem, but none of the editors I use are listed there.

I think it’s all about situation. For SQL white space is used to format the code, so multi line is the way to go. For HTML, I echo as I would have typed the html, ie each line is echoed separately.

What’s wrong with line wrap for long text?

Seems to be fixed, at least in NotePad++ (though it doesn’t highlight SQL keywords or HTML keywords in a string - though how would it know that the string is meant to be sql).

I have one realistic reason why embedded newlines may be an issue - testing. The resulting string differs depending on how far it is indented, and on whether spaces or tabs are used to indent it.

That has been the cause of some issues when it comes to unit testing.

Hi spivurno.
Just remember one simple rule: not a single syntax issue have any performance importance. You can use any syntax you wish and never worry about performance.

So, I am totally agree with hash - it won’t make any significant difference.

Also bear in mind that these coding tips aren’t treasure of wisdom.
Some of them obsoleted and some of them should be titled “Coding standards” and separated from the tips and some of them just not a truth.
That topic badly need to be edited and sorted out.

I write SQL as SpacePhoenix has said.
For multi line string I prefer this:

echo '<table> <tr>
        <td> </td>
       </tr>
    </table>
   ';

or if string has lots of variables then for making it more clear
I use concatenation for each line.

But writing lots of echo is not very good as this slow down the program.
And if you getting something in loop then better to use something like:

for (…)
{
$str .= ‘dynamic text here from loop’;
}
echo $str;

Now this will not output each line and html rendering will also be fast. You will notice it when you output lots of content (may be in report) etc.

For that HTML string I would do it something like:

echo '    <table>\

            <tr>\

                <td> </td>\

            </tr>\

        </table>\
';

I prefer to have the
in there so that when I’m trying to fix validation errors in the HTML it makes it easier to spot them.

Please test your “preferable” code before posting.

That will output a bunch of
to your page. Not new line, the characters \ and n.

E: lol alt tabbed on that one for a while

For each echo/print statement, output is sendt to the browser (unless output buffering is in place).

The amount of data transmitted would be the same, in either case.
However, the amount of trafic between server and client is not.

Many echo/prints = many small transmissions.
Few echo/prints = few larger transmissions.

I prefer few over many.


echo '<table>
    <tr>
        <td>some text</td>
        <td>'.$variable.'</td>
    </tr>
</table>
';

// or
$output = '<table>
    <tr>
        <td>some text</td>
        <td>'.$variable.'</td>
    </tr>
</table>
';
echo $output;

Hi zalucius.
Do you really understand the technology? Define “transmission” then. What do you mean?
What if we also have HTTP server between PHP and client?

Thank you for all your thoughts. Very helpful. :slight_smile:

Hi Shrapnel_N5,

Im not too deep into how the exact inner workings of PHP and output to client works. Thus “transmission” might have been a bad choice of word…
In my book, every echo/print statement results in some data being sent somewhere.

Keeping the data on the PHP side, until all output is ready, will result in fewer connections/streams/transmissions,… or what its called…

I tried to do a little digging on the subject, but didnt really find anything usefull… perhaps you have some useful links/topics I could have a look at?

Honestly, if your worrying about whether calling echo or print once or multiple times is going to affect efficiency you need to step back and get your priorities in order. For me it comes down what is more readable. If using several calls to echo is more readable then a single call then so be it. It just depends on the situation there isn’t really any absolute. The same can be said for printf, sprintf vs. echo and string concatenation. It more or less comes down to personal preference considering the code is going to conduct itself in pretty much the same way. Micromanaging these things are hardly worth the time of day.