1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

A question to php pros

Discussion in 'PHP' started by qwikad.com, Apr 29, 2018.

  1. #1
    So, I always thought that it is better to have just one opening tag and one closing tag when it comes to php. So I always thought this was ideal:

    <?php
    if($something){
    echo '<p>Hello World.</p>';
    }
    ?>
    Code (markup):
    However, I read that it is better not to send HTML to php. Like it is explained here. So this appears to be a better way:

    <?php if($something){?>
    <p>Hello World.</p>
    <?php }?>
    Code (markup):
    My question is will the second example perform slower if the script has DOZENS of closing and opening tags?
    SEMrush
    Is the second example actually better? Personally, I doubt it, but would like to know what php developers think.
     
    qwikad.com, Apr 29, 2018 IP
    SEMrush
  2. sarahk

    sarahk iTamer Staff

    Messages:
    24,421
    Likes Received:
    3,287
    Best Answers:
    94
    Trophy Points:
    615
    #2
    WordPress jumps in and out of php constantly and that I know @deathshadow describes that as scriptardery or something similar.
    I find it less readable and tend to err on the side of readability and maintainability. The processing power of the servers compared to the load jumping in and out adds means your script won't be slower.

    A better example might be
    foreach($totals as $k => $v){
    <tr>
    <td><?php echo $k</td>
    <td><?php echo $v; ?></td>
    </tr>
    }
    PHP:
    versus
    foreach($totals as $k => $v){
    echo "<tr><td>{$k}</td><td>{$v}</td></tr>";
    }
    PHP:
    There will be a time to use both approaches and it depends on the other code around it as to which is going to be the most readable when you have to come back and make changes.


    [​IMG]
     
    sarahk, Apr 29, 2018 IP
    qwikad.com likes this.
  3. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    5,549
    Likes Received:
    1,032
    Best Answers:
    19
    Trophy Points:
    400
    #3
    So it's not as much about the speed as it is about readability and maintenance then. I had a script, a long one, when I rewrote it (it had probably 100 start and stop tags) I swear it seems to be performing faster now, like by a second.
     
    qwikad.com, Apr 29, 2018 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,651
    Likes Received:
    1,561
    Best Answers:
    225
    Trophy Points:
    515
    #4
    There is a speed component, but it plays to the complexity of how you open/close.

    The double quote approach to strings, or the curly bracket approach are the slowest as they involve the most string processing. In particular they rely on string processing on EVERY call, so this:

    
    foreach($totals as $k => $v){
      echo "
        <tr>
          <td>{$k}</td>
          <td>{$v}</td>
        </tr>";
    }
    
    Code (markup):
    example @sarahk gave would be the slowest as it is using BOTH the brackets AND double quotes.

    THIS ugly mess and it's ilk:

    
    <?php foreach($totals as $k => $v) { ?>
    	<tr>
    		<td><?php echo $k; ?></td>
    		<td><?php echo $v; ?></td>
    	</tr>
    <?php } ?>
    
    Code (markup):
    Or this being the 'proper' way of doing that if you're going to willy-nilly open/close PHP for no good reason:

    
    <?php foreach ($totals as $k => $v): ?>
    	<tr>
    		<td><?= $k; ?></td>
    		<td><?= $v; ?></td>
    	</tr>
    <?php endforeach; ?>
    
    Code (markup):
    Would be faster.... BUT, so would this:

    foreach($totals as $k => $v) echo '
    	<tr>
    		<td>', $k, '</td>
    		<td>', $v, '</td>
    	</tr>';
    
    Code (markup):
    In fact, that last one is the fastest and cleanest of them because there's only one actual echo command and then delimited output, using simple single quoted strings! Also being less code it parses faster if the routine isn't in the bytecode cache, the static strings are separated out into the data area resulting in better memory usage, and it also results in a smaller bytecode increasing the odds of it remaining in the cache.

    That stackExchange link you shared is filled with nothing but bad practices and card stacked examples.

    To me the constant opening and closing of PHP is just a waste of typing, hinders clarity, AND it's not any faster -- it's usually slower -- than just using single quote strings with comma delimits on echo. that's why IMHO double quote strings with inlined variables AND the PHP shorttags should be stricken from PHP entirely -- so PHP can behave more like a real programming language instead of a half-assed scripting one.

    Hence why if I were writing your original example, I wouldn't be wasting time on the brackets for NOTHING. If you're only doing one command, just huffing do it!

    
    if ($something) echo '
      <p>Hello World.</p>';
    
    Code (markup):
    Maintaining only one <?php per file (as the FIRST thing in EVERY damned file) with ZERO ?> whatsoever. Also gives you a chance to put formatting in your output making debugging the output easier. Good rule of thumb, if you see genuine benefits from whitespace stripping / minifying your HTML (apart from as helpful reminders NOT to paste stuff between certain tags), there's something WRONG with the HTML.

    Hence why if you dig into one of my template files, you'll find things like this:

    
    function template_header() {
    
    	echo '<!DOCTYPE html><html lang="',
    		Settings::value('contentLang'),
    		'"><head><meta charset="',
    		Settings::value('encoding'), '">
    <base href="', BASE_HTTP, '">';
    
    	if ($temp = Settings::section('namedContentMeta'))
    		foreach ($temp as $name => $content) {
    			echo '
    <meta';
    			if (is_array($content)) template_header_attrPairs($content);
    			else echo ' content="', $content, '"';
    			echo '>';
    		}
    
    Code (markup):
    Coding that with endless <?php, <?= and ?> would make me want to jab out my eyeballs.

    edit -- f*** sake that looks like crap with colour syntax highlighting. THIS is why I hate that illegible hard to follow hard to use bullshit!
     
    Last edited: Apr 29, 2018
    deathshadow, Apr 29, 2018 IP
  5. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,651
    Likes Received:
    1,561
    Best Answers:
    225
    Trophy Points:
    515
    #5
    Oh, a few other details to be aware of is the HEADACHES not comma delimiting and using double quotes can create in terms of execution order. I'd sooner see you using endless pointless <?php ?> than double quoted strings with variables inside them! -- and I'm ALWAYS saying "don't open/close PHP for nothing".

    MORE so in terms of comma delimiting vs. string addition. Avoid string addition unless you HAVE to use it, like inside a ternary operator. If you can use comma delimited echo (or willy-nilly php opens/closes) do so.

    Czech this out:

    
    function test() { echo 'test'; }
    
    echo 'This is a ' . test() . '<br>'; // this one's jacked
    
    echo 'This is a ', test(), '<br>'; // this runs as you'd expect.
    
    Code (markup):
    Because string addition has to run the function BEFORE the addtion takes place, more memory is reserved to generate the result inside, and the echo inside the function runs BEFORE the string is built. As such the output from the above snippet is:

    
    testThis is a <br>
    This is a test<br>
    
    Code (markup):
    It's often laughable how often people screw that up, especially in turdpress since it uses the function with echo/output instead of a result method ALL the time. You use comma delimits or <?php ?> it will at least execute in the order you'd expect!

    In that way, I think the overuse of double quoted strings and string addition when they both SUCK OUT LOUD at code clarity and performance is where the MYTH of "use <?php ?> over echo" came from. You avoid double quoted strings except for when you need them and comma delimit your echo, it's faster, lower memory use, and just fine and dandy!

    Kind of like the people who think that "you can't use variable functions with language constructs like echo" means you can't do this:

    
    echo $test();
    
    Code (markup):
    Which is not at ALL what the documentation means. It means you can't do this:

    
    $test = 'echo';
    $test('this is test');
    
    Code (markup):
    Just like the mouth-breathing halfwitted dumbass dipshits on the HTML side who turned "use EM and STRONG when their semantic meaning is more appropriate" into "never use B and I" or "B and I are deprecated" -- or "don't use tables for layout" into "never use tables". NOT what the bloody specification or anyone who knows the first damned thing about semantics was talking about!!!

    Bottom line, avoid using double quotes and string addition, there's not a damned thing wrong with echo. You compare it to PHP shorttags it's a hair better. You compare double quoted strings, inlined variables, heredoc, nowdoc, and all that other bloated halfwit crap to PHP shorrtags, and all you've done is stack the deck against echo with crappy coding techniques.

    .. and if you use singles server-side you can use doubles more easily in your HTML output, so your HTML doesn't look like crap! In fact, I use the presence of single quotes in someone's HTML created by PHP as a indicator of if the developer is qualified to be writing PHP professionally or not. I see:

    
    <a href='whatever' style='color:red'>
    
    Code (markup):
    I automatically assume there's something wrong with the server-side code's methodology! Well and the inlined style also makes me think they're not qualified to write HTML either.

    Hence why to me this:
    
    echo "<tr><td>{$k}</td><td>{$v}</td></tr>";
    
    Code (markup):
    Is probably the DUMBEST way of handling an echo with variables in the markup possible! At least compared to:

    
    echo '<tr><td>', $k, '</td><td>', $v, '</td></tr>';
    
    Code (markup):
    Where the single quoted strings parse faster, are sent to echo in turn from static references instead of allocating more memory, the clarity the whitespace formatting provides, etc, etc, etc...
     
    Last edited: Apr 29, 2018
    deathshadow, Apr 29, 2018 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,651
    Likes Received:
    1,561
    Best Answers:
    225
    Trophy Points:
    515
    #6
    No, scripttardery is almost exclusively "JavaScript for nothing of value".

    This is just opening PHP willy-nilly for no reason other than to make the code harder to follow and prevent static string storage due to oddities in how the parser handles that. Never been able to come up with a cutesy name for it. I just find it ugly and harder to maintain compared to echo with single quote strings and comma delimits.
     
    deathshadow, Apr 29, 2018 IP
    sarahk likes this.
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,651
    Likes Received:
    1,561
    Best Answers:
    225
    Trophy Points:
    515
    #7
    ACTUALLY I stand corrected. In PHP 5.x/earlier the double quote version with inlines is slower, but they seem to have optimized it for PHP 7 -- the memory use is still higher but it's now actually FASTER to do it the 'dumbass' way in terms of execution time.

    So now it comes down to code cleanliness and how big a deal is the memory footprint for you -- since excessive memory use in lots of requests can still gut your speed even if on paper the execution time is faster. JOY.

    They must be handling it at the parser level instead of the execution level now. Hrm... that could cause problems in terms of realtime execution, wonder how they handle that.

    Not sure how they sped up the inefficient fprint style methodology so much, unless their shorttags and comma delimit implementation is in equal need of optimiization under the hood.
     
    Last edited: Apr 29, 2018
    deathshadow, Apr 29, 2018 IP
  8. phpmillion

    phpmillion Member

    Messages:
    142
    Likes Received:
    11
    Best Answers:
    4
    Trophy Points:
    45
    #8
    If you care about readability and maintenance, your best approach is not to use spaghetti code at all. That is to say, consider using PHP templating engine, which makes maintenance and updates easier. Sure, it might take some time to migrate from spaghetti to templating engine (depends on the current code of your script and how big the script is), but it will save you lots of time later.

    I personally like Twig because it's super-easy to learn and use.
     
    phpmillion, Apr 30, 2018 IP
  9. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,651
    Likes Received:
    1,561
    Best Answers:
    225
    Trophy Points:
    515
    #9
    Oh because those fat bloated train wrecks of stupidity are any huffing better?!? With the massive string processing, restrictive nature, and pointlessness of running a template engine on top of PHP when PHP itself IS A HUFFING TEMPLATE ENGINE?!?

    Seriously, just whiskey tango foxtrot! PARTICULARLY when it's syntax is damned near PHP shorttags just with {% instead of <? -- that's some pure huffing derp right there!

    But what can I expect from something where the creators idea of "concise" is what I label as annoyingly, aggravatingly, and pointlessly cryptic! That it then expects you to dump every result to some fatass dumbass array doubling-down or more on the memory footprint? Herpafreakingderp!

    You'd ALMOST think it was made by people not qualified to write a single line of HTML... OH WAIT!!!

    
      <div id="sln"></div>
        <div class="hd">
          <div class="illustration png_fix">
            <div class="content">
              <div class="sensio_product">
                <img class="png_fix" src="/images/sensio-labs-product.svg" alt="a SensioLabs Product" height="18" />
              </div>
              <div class="clearfix">
                <div class="logo_header"><a href="/">Twig</a></div>
                <h1 class="title_header">
                  The flexible, fast, and secure<br />template engine for PHP
                </h1>
              </div>
    
              <div class="menu">
                <ul>
                  <li><a class="active" href="/">ABOUT</a></li>
                  <li><a href="/doc/2.x/">DOCUMENTATION</a></li>
                  <li><a href="/development">DEVELOPMENT</a></li>
                  <li><a href="/contributors">CONTRIBUTORS</a></li>
                </ul>
              </div>
            </div>
          </div>
        </div>
    
    Code (markup):
    Yeah, that. 1k of rubbish markup doing half a K's job... Just like this train wreck of ineptitude and ignorance:

    
        <link href="/css/reset-min.css" rel="stylesheet" type="text/css" />
        <link href="/css/base.css" rel="stylesheet" type="text/css" />
        <link href="/css/colors.css" rel="stylesheet" type="text/css" />
        <link href="/css/code.css" rel="stylesheet" type="text/css" />
        <link href="/css/pygments.css" rel="stylesheet" type="text/css" />
        <link href="//connect.sensiolabs.com/css/sln.css" rel="stylesheet" type="text/css" media="all" />
    
    Code (markup):
    ...and we're supposed to trust that these jokers have any business telling us how to make templates?!? BULLSHIT!

    Lands sake, what's wrong with just using PHP to do all that crap they're wasting code, memory, and processing time on?!? I mean, other than their pathetic card stacked scam artist examples?

    Of course the "composer" requirement that results in most affordable web hosts telling you to go take a flying hike (same problem node.js faces) limiting you to pretty much self-hosting and self-managing on a VPS really puts a dent in your target audience pool as well. Cute if you're only building in-house with complete control, near useless on a commercial project.
     
    Last edited: Apr 30, 2018
    deathshadow, Apr 30, 2018 IP
  10. phpmillion

    phpmillion Member

    Messages:
    142
    Likes Received:
    11
    Best Answers:
    4
    Trophy Points:
    45
    #10
    Yes, everyone knows you are the only real coder on the planet and everyone else (let it be beginner programmers, or developers responsible for coding/optimizing for world's biggest companies) who use any type of library are fu**ers, losers, and idiots (or lazy bastards at least).
     
    phpmillion, Apr 30, 2018 IP
  11. JEET

    JEET Well-Known Member

    Messages:
    2,187
    Likes Received:
    100
    Best Answers:
    1
    Trophy Points:
    185
    #11
    Long back when I was starting, I read somewhere that the second method is better.
    The one with multiple open and close tags
    The article said that page load time is much faster this way.
    Because when we start a single tag at the beginning, and close it at the very end,
    then php holds the output and doesn't send it to the browser until all processing is complete.

    However, when tags are opened and closed again and again,
    then PHP keeps sending output to the browser as soon as the tag is closed...

    Try these 2 codes in your localhost
    Increase $limit if you have to...

    <?php
    $limit= 100000;
    for($x=0; $x<$limit; ++$x){ echo "my name<br />"; }
    ?>

    --- second way

    <?php
    $limit= 100000;
    for($x=0; $x<$limit; ++$x){
    ?>
    my name<br />
    <?php
    }
    ?>
     
    JEET, Apr 30, 2018 IP
  12. qwikad.com

    qwikad.com Illustrious Member Affiliate Manager

    Messages:
    5,549
    Likes Received:
    1,032
    Best Answers:
    19
    Trophy Points:
    400
    #12
    @JEET but what if there are a thousand (quite possible in some scripts) of start and stop tags, then the PHP will have to send it to the browser a thousands times. Like I mentioned above, I cleaned up one script (removed extra start / stop tags) and it seems to be performing faster, but then again, I have nothing to compare it to since I no longer have the old version.

    @deathshadow I almost never use double quotes in echo or curly brackets unless it's absolutely impossible not to use them. I am not a coder, I usually find good scripts and try to make them work faster / better, thus the original question. So far it seems like there are two opposing views. Reading your posts I gather multiple openings / closing tags is nonsense.

    @phpmillion One of the sites I purchased works using PHP templating and to be honest with you I am not a big fan of that approach. Quite possible it's because of the way the site designed.
     
    qwikad.com, Apr 30, 2018 IP
  13. sarahk

    sarahk iTamer Staff

    Messages:
    24,421
    Likes Received:
    3,287
    Best Answers:
    94
    Trophy Points:
    615
    #13
    Your site should be using MVC anyway which means any logic in the View is pretty lightweight. Templating systems were the precursor, from the days when we realised we had to separate the content but weren't quite sure how to do it.
     
    sarahk, Apr 30, 2018 IP
  14. JEET

    JEET Well-Known Member

    Messages:
    2,187
    Likes Received:
    100
    Best Answers:
    1
    Trophy Points:
    185
    #14
    qwikad I too find multiple opening and closing tags very annoying.
    This is why I too use a single tag approach, but in the past I've seen this happening in real time.
    One of my scripts was making an API call to Yahoo, and the call was taking time.
    In the single tag approach, nothing was sent to the browser until entire processing was complete.
    Then I switched that script to use multiple tags like below.
    All the data before the API call got displayed in the browser, and then when API call was done, the rest came in.
    Meaning the visitor did not wait, staring at a blank page...
    Basically, the response time of the website got improved significantly.

    Also I found that using multiple mysql connection approach is faster than single connection approach.
    Like earlier I used to connect to database at top, and close DB at the end.
    Later I found that connecting to DB only when you need to send a query improved the total response time of the site...
    Since then I've been sending queries through a function.
    The function connects to DB, executes query, closes DB and returns array of output to a variable...

    Single approach was like this:
    <?php
    $title='Page title';
    $beforeCall='<p> This is some html </p>';
    $api= getAPIData();
    $after='<p> This is more data </p>';
    $html='<html><head><title>'. $title. '</title></head><body>
    '. $before. '
    '. $api. '
    '. $after. '
    </body></html>';
    echo $html;
    ?>
    PHP:
    Multiple tag approach was like this:
    <?php
    $title='This is page title';
    ?>
    <html><head><title><?php echo $title; ?></title></head><body>
    <?php
    $before='This is before API';
    ?>
    <p> Some basic designing etc
    <?php echo $before; ?>
    <p> Other html
    <?php
    $api=getApiData();
    echo $api;
    ?>
    <p> Other html
    <?php
    $after='This is data after API';
    echo $after;
    ?>
    </body></html>
    PHP:

    All the data before API call got displayed in the browser without any delay.
    Of course, the HTML structure was DIV based, not TABLE based.
     
    JEET, May 1, 2018 IP
  15. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,651
    Likes Received:
    1,561
    Best Answers:
    225
    Trophy Points:
    515
    #15
    @JEET, all that string addition in the first one is just wasting MASSIVE amounts of memory, more so if gzip compression is on where the entire output is being buffered anyways. That first example -- really one shouldn't ever write code that way. It's also an ugly way of handling it.

    
    <?php
    $title='Page title';
    $beforeCall='<p> This is some html </p>';
    $api= getAPIData();
    $after='<p> This is more data </p>';
    echo '<html><head><title>', $title, '</title></head><body>
    ', $before, '
    ', $api, '
    ', $after, '
    </body></html>';
    
    Code (markup):
    Assuming all those "variables for nothing" are placeholders for data pulled from databases, but even then that CAN be a bit wasteful and inefficient on the memory side handling all the processing first -- though it CAN execute faster so you have to weigh available memory -- and the impact multiple requests of a fatter footprint -- vs. execution speed.

    A bit like old school assembly programming, where optimizing for size, optimizing for speed, and optimizing for ease of development and maintenance are three separate things -- and you only get to pick one. A LOT of times you can speed things up by throwing more RAM at it, or dupe yourself into thinking it's faster when run as a standalone in a low load testing environment, then sit there scratching your head wondering why things go bits-up face-down on a sever with actual traffic.

    Kind of like the "condense everything to one JOINed query" mantra that as a standalone on low traffic testing is faster, but uses so much memory that in a production environment it's slower than running multiple separate queries. Lost count of the number of times going in and breaking up massive queries (with massive REDUNDANT data results) fixed hosting woes on various client's apps.

    In that way, techniques like massive string parsing (how many template systems that sit atop PHP function -- basically any that don't "compile" to PHP), pulling your entire data set into massive arrays before calling your template, and making endless "variables for nothing" are all bad practice since you're just increasing the memory footprint for no real good reason.

    Hence why I'd likely never have code like that. My separation of output from data still means the data handler at least CALLS the template when it's ready. I may have some smaller values -- title, the menu anchors and text, etc, etc -- stored ahead of time, but the content area? Not so much.
     
    deathshadow, May 2, 2018 IP
    JEET likes this.
  16. gutterboy

    gutterboy Member

    Messages:
    33
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    28
    #16
    In general I don't think you're going to notice any speed differences by whatever method you choose, it more depends on code readability and making it easier to maintain as well. Like, it is generally cleaner to separate your code, but if you're just needing to insert a single line it may be better to just use an echo for that single instance rather than opening and closing PHP tags just for that one line; but when you have big chunks of HTML then it's cleaner to close and reopen PHP rather than have a bunch of echo statements.

    One thing to look at however are PHP "HEREDOCS" and "NOWDOCS"; these both allow you to output content a bit cleaner than with a bunch of echo statements and don't require any escaping when you use quotes inside of them; the difference being parsing is done inside of HEREDOCS, which means you can use variables inside of them like you can within double-quotes and with NOWDOCS they behave like single-quoted strings, no parsing is done.

    More info and gotchas here: http://php.net/manual/en/language.types.string.php

    Lastly, I don't recommend it now, but once you are a bit more experienced with PHP, I would recommend reading up on the MVC methodology; this is basically a cleaner way to separate your code.
     
    gutterboy, May 14, 2018 IP
    sarahk and qwikad.com like this.
  17. deathshadow

    deathshadow Acclaimed Member

    Messages:
    8,651
    Likes Received:
    1,561
    Best Answers:
    225
    Trophy Points:
    515
    #17
    ... and

    ... as opposed to just ONE echo with comma delimits? Remember, PHP strings are whitespace neutral so apart from:

    (which is a good point) there are ZERO legitimate differences between heredoc/nowdoc and normal strings -- well apart from IMHO being HARDER to work with.

    But they in often seems I look at how to use strings in PHP differently from others, since I bother using comma delimits in my echos. I watch people use string addition with double quotes and shake my head wondering why people are making their lives so much harder. It's like they WANT quoted strings to suck so they do everything they can to make it so.
     
    deathshadow, May 14, 2018 IP
  18. gutterboy

    gutterboy Member

    Messages:
    33
    Likes Received:
    9
    Best Answers:
    0
    Trophy Points:
    28
    #18
    Well I suppose you could use a multi-line echo statement if you wish, I've just never been a fan of them, but I digress.

    I think the fact you don't need to escape quotes within them is pretty legitimate; which in practice creates cleaner code.

    I personally very rarely use double quotes strings as I usually don't see the point; yes they get parsed, but why make PHP parse them when it probably doesn't need to? On top of that, I find the code to be far more readable when you separate your functional code from your static code, such as:

    
    $name = 'gutterboy';
    $str = 'My name is ' . $name . '; nice to meet you!';
    
    PHP:
    This way you can clearly see that there is a variable in the string without having to look through it all because a double-quoted string may contain a variable; and on top of that PHP only parses what it needs to.
     
    gutterboy, May 15, 2018 IP