PHP Alternative Control Structures, any drawbacks? - php

I've been working with PHP code that generates HTML without any templating, and it's quite spaghetti and difficult to read with the way they've structured it. One way to drastically improve following the flow I've noticed is to use : endif instead of { } blocks in some cases to increase readability. (See http://php.net/manual/en/control-structures.alternative-syntax.php)
Is this portable?
Is this standard?
Is this slower in any significant way (I understand it takes more chars)
Cheers!

Is this portable?
Yes
Is this standard?
Yes
Is this slower in any significant way (I understand it takes more chars)
I don't know.
But imho it increases readability and maintainability very much if you use it in combination with HTML.
Example:
<?php foreach($array as $value): ?>
<div>
<?php if($value == "foo"): ?>
<p><?php echo $value; ?></p>
<?php endif; ?>
</div>
<?php endforeach; ?>
vs
<?php foreach($array as $value) { ?>
<div>
<?php if($value == "foo") { ?>
<p><?php echo $value; ?></p>
<?php } ?>
</div>
<?php } ?>
It is just a small example but I think endif and endforeach are much easier to spot as <?php } ?>. So yes, definitely use it with HTML!
I don't use it anywhere else though because in "normal" code I find it more difficult to read.

Personally, I detest them, but they're part of the language. They haven't been deprecated and I doubt they'll be removed anytime soon.
The thing you have to be careful about is that you can't mix the two syntaxes in the same control block (as the manual page says).
I don't find them any more readable. Identation gives enough clue. If you have blocks long enough that you see yourself using these control structures or } //end of while, you should refactor your code.

PHP Alternative Control Structures, any drawbacks?
Yes, you can't use % in vim to bounce between the beginning and end of the block. Just sayin.

to answer directly: Yes, it is standard and portable and it isn't any slower. It is a simple alternative to the standard curly-brace syntax. Whether or not you choose to use it is up to you as a style choice.
Personally, having been taught and used c-style languages my whole programming career (thus far) i prefer the curly braces with a simple comment after the end of the } curly brace that tells you what it is ending.

The only drawback that i see is that in an editor like sublime text, there are options like
"Jump to Matching Bracket" and "Expand Selection to Brackets" which wont work with the alternate syntax

Related

Is using alternative PHP syntax for control structures PSR compliant? (when mixed with HTML)

I have looked through the PHP-Fig website for any PSR related to alternative PHP syntax for control structures but failed to find anything about it.
The alternative syntax is this for example:
<?php foreach ($arr as $foo) : ?>
<h1>block start</h1>
<?php if ($foo === 'test') : ?>
<a>Case1</a>
<?php elseif ($foo === 'test2') : ?>
<a>Case2</a>
<?php else : ?>
<a>CaseElse</a>
<?php endif; ?>
<h1>block end</h1>
<?php endforeach; ?>
So is it just not defined and thus ok to use, or is it not compliant since there is no mention about it in the coding style sections?
According to Section 5 of PSR-12 (Control Structures):
The body of each structure MUST be enclosed by braces. This standardizes how the structures look and reduces the likelihood of introducing errors as new lines get added to the body.
This means that endif, endwhile, endfor, endforeach, endswitch are not compliant with PSR-12.
It would be helpful if PSR-12 was more explicit about this, as it is easy to overlook or misinterpret this.

Curly braces or colon-endif statements in PHP - which one provides better performance and code compatibility?

I was looking through many snippets of code, and I have found that people can use the following two methods in an if statement:
Method 1:
<?php
if ($condition) {
// Do this
}
?>
Method 2:
<?php
if ($condition):
// Do this
endif;
?>
So which method is more compatible with PHP compilers and versions with PHP, or is there no discernible difference between the two?
Most of the time the alternative (endif) syntax is used in view scripts. It's often hard to see/notice the end of an if statement since a curly brace only takes up one character, when you're at the bottom of a file, it's hard to tell if it's the end of an if or a foreach. For example:
<?php if ($condition): ?>
<div>a huge block of html</div>
<?php endif; ?>
They are both exactly equivalent. Consult your organization's style guide to determine which you should use.
This alternative syntax is in no way different than the, perhaps, more familiar syntax. Just don't mix the two. Similar syntax exists for while, for, foreach, and switch.
Typically you should choose your preferred syntax based upon readability, and your teams preference.
What really might throw you is when you begin to see "if statements" which misuse logical conjunction operators like the following:
isset( $value ) AND print( $value );
As I've seen until now, in my app, there is no difference between them, but you can have a lot of problem if you'll mixt them without a rule because it's possible to get some errors and you will search a curly but you have not used curly.
Choose one syntax an use exclusive.
The only difference is seen in very large documents and projects. My company uses braces rather then endif, endelse... as we work on very large projects. When you compare file sizes there is a benefit to using braces. Smaller files load faster so we work to reduce every byte we can. We comment out the end brace to make it easier to identify on testing and then delete all comments for production.

Php: what's the difference between while...endwhile; and while { // stuff here }

What's the difference between
while (expression):
// do stuff
endwhile;
and
while {
}
There is no functional difference.
In practical use I find that:
while (expression):
// do stuff
endwhile;
Is more readable for the designers when you are embedding php code within html. IE:
<? while ($cssClass = array_pop($array)): ?>
<li class="<?=$cssClass?>">
<? endwhile; ?>
Whereas:
while {
}
Is more readable within a php code block.
There's no difference, it comes down to personal preference.
The difference is negligible when the code is actually run, but when coding I find that typing the brackets is (1): quicker, (2): more conventional, and (3): allows for less chance of error (endwhle anyone?).
As a bonus, the editor I use auto-formats the while loops (with brackets, by default) and down the road, if anything is off, the built-in bracket-matching function will catch it.
There's no real difference when writing code.
There can be a difference in levels of convenience in very special circumstances. For example, suppose you are writing a template engine that converts template code to native PHP code which is then cached and executed directly for speed.
In this case, the fact that while...endwhile; avoids using braces may allow you to simplify your parsing algorithm if e.g. it recognizes variables that should be substituted with a syntax like {$var}, which also uses braces.
Of course this is a pretty small benefit in a really extraordinary situation, but you take what you can. :)

what is the difference between these two foreach loops?

I have seen in cakephp that foreach loop is used like this
foreach($tags as $tag) :
\\code here
endforeach;
and I used to write this style of foreach
foreach($tags as $tag)
{
//code here
}
what is the difference between these two foeach loops and which one is better and makes more sense to implement ?
Thanks
They are equivalent, but the second first is sometimes more readable when your PHP is embedded with HTML.
They are identical. I'd use the ones with the curly braces though, since the syntax is more like other PHP constructs, C, C++, Java, etc..
The first one dates from an early PHP syntax (before PHP 4) and the second one is what's generally accepted now. IMHO I'd avoid using the first one and would always use curly braces, even for something like
<?php foreach ($foo as $f) { ?>
<div><?= $f ?></div>
<?php } ?>
Because many editors have brace highlighting and it's just better that way :)
They are equivalent, but the first one sometimes is more readable when your PHP is embedded in HTML.
:)~
As of it's equality, no method can be called "better", and can be only subject of agreement.
They are completely identical, thus the first one is most likely to be used because it allows one to let the braces go, you don't need to remember where the braces are and what is open when adding a large part of other codes or HTML design.
Just like the alternative for IF statement:
<?php
if ($foo):
echo "is ok\n";
elseif ($bar):
echo "not ok\n";
else:
echo "dont't know\n";
endif;
?>
It comes down to personal or team coding standards. I prefer the {} option as it makes more universally readable code. True, it gets messy in HTML, but again with a coding standard you can ease that.
If you have a lot of HTML and PHP within the loop, using the : option can create serious confusion lower down in the code, especially if the loop runs off the bottom of the page. Syntax highlighting with {} will let you identify the loop contents much more easily.

Is there a speed difference between <?php echo $var; ?> and <?=$var?>?

Is there any speed difference between these two versions?
<?php echo $var; ?>
<?=$var?>
Which do you recommend, and why?
Performance difference is insignificant. Moreover, with use of APC, performance difference is zero, null, nada.
Short tags are problematic within XML, because <? is also markup for XML processing tag. So if you're writing code that should be portable, use the long form.
See short_open_tag description in http://www.php.net/manual/en/ini.core.php
Technically the parser has to parse every character of the longer version, and there's a few more characters for every transfer.
If your webserver doesn't "pre-compile" (ie: cache tokenized PHP pages) then there is a slight performance difference. This should be insignificant except, perhaps, when you start talking about billions of runs.
Performance wise it is insignificant.
Proper usage says to use the longer one, as it is more portable. Personally? I do the shorter one.
No, they are identical. If you like typing a lot use <?php echo $var; ?>, otherwise just save time with <?=$var?>.
Which do you recommend
Neither, unless you really want to allow HTML injection. (99% of the time, you don't.)
<?php echo htmlspecialchars($var); ?>
Or define a function that does echo(htmlspecialchars($arg)) with a shorter name to avoid all that typing.
in php 5.3 short tag ASP-style <% %> support will be deprecated, try to avoid this and rewrite the code to the '<?php echo' format, because u cant use <?xml ?> inline for example.
These two lines of code are identical.
I'm adding a late answer because nobody has demonstrated this yet, but the answer is unequivocally no, there is no performance difference specifically because there is no difference at all in how PHP executes these two lines of code.
The interpreter sees the identical code in both cases. The parser produces the exact same AST, because <?= is fundamentally identical to <?php echo. There is no difference in the instructions the interpreter runs when you write <?= vs <?php echo.
By installing php-ast you can examine the AST produced by both lines of code.
Given these two cases...
# CASE 1
<?php echo $i %>
# CASE 2
<?= $i ?>
The abstract syntax tree for both is identical:
case 1
AST_STMT_LIST
0: AST_ECHO
expr: AST_VAR
name: "i"
case 2
AST_STMT_LIST
0: AST_ECHO
expr: AST_VAR
name: "i"
This means PHP cannot tell the difference between these at run time, never mind experiencing some kind of performance difference.
The code to produce this output is as follows, and uses util.php:
<?php
require('util.php');
echo "case 1\n";
echo ast_dump(ast\parse_code('<?php echo $i ?>', $version=50));
echo "\n";
echo "case 2\n";
echo ast_dump(ast\parse_code('<?= $i ?>', $version=50));
echo "\n";
Optimization is irrelevant here. The choice comes down to personal preference, especially since <?= is always available, has nothing to do with short tags, has never been deprecated and is not slated to be removed from the language.
I think the second one requires the short_open_tag (in PHP.ini) to be set to true.
Meaning there is a chance it's turned off on some webservers.
The speed difference depends on how fast you can type those 9 extra characters.
It can also improve the readability of your code, but this is debatable.
If your talking about execution-speed there is no noticable difference.
Don't try to optimize with these, it's useless. Instead, deactivate allow_short_tags (because of problems when loading XML files) and write clean, readable and understandable code.
Even if there may be a slight difference (which is definitely lower than 10%), it's useles to optimize with it. If your scripts are slow, look at your loops first. Most of the time you can win a lot more performance by optimizing the programms flow than by using strange syntax.

Categories