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. :)
Related
if I have code like that
if($abc==true) {
//code code code
} else {
// other code, other code
}
So if $abc is true will the "other code" be compiled?
So is this irrelevant if there is a lot of "code" performance wise?
PHP is a parsed (and therefore "compiled") at runtime. All of the code is processed, regardless of reachability. For instance:
<?php
echo "Hello, World!";
exit;
DERP!!
?>
Will fail with a Parse Error rather than printing "Hello, World!", even though the derp can't ever be reached.
Yes, it will be compiled (actually read, tokenized and parsed); PHP has no way of knowing what value will be assumed by $abc at runtime.
You can reduce the load somewhat (but only if it is REALLY a lot of code!) by using include() inside the IFs:
if (condition)
{
include('true.php');
}
else
{
include('false.php');
}
But note that this way you will load two files instead of one. Usually, the overhead of the extra file makes the game not worth the effort.
However, if the IF is really a lot lot lot of code, then dividing it in several files might be a good idea maintenance-wise. Refactoring to remove the IF from the program flow would be even better!
Although the entire code is 'parsed' for errors at runtime, the flow of code will only go in one direction at that 'if' point, so there's basically no speed performance issue.
It's really not worth worrying about, especially since flow control statements such as 'if' are probably the most vital elements of programming. You can't get by without them, really.
What performance problems are you concerned about? PHP is an interpreted language which means your files are parsed, tokenized, and executed on every request. The entire file needs to be parsed and tokenized for syntax errors no matter what. What is executed depends on your control flow statements, like the if in your example.
If you're concerned about extra parsing, you can refactor your code to include another file based on the result of a control flow statement.
$x = 1;
if($x === 1) {
include_once './myFile.php';
}
else {
// Something Else.
}
Though I can't really think of a huge reason related to performance as to why you would want to do that.
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.
I've recently been exposed to a PHP practice of only using a single echo statement. So effectively the view is built in a view class and a function exists to return the HTML.
This is then echoed, with this being the only echo statement in the page:
$output_html = $obj_cars_view->get_output_html();
echo $output_html;
N.B cars was the first real life object I thought of and is unrelated, I'm more interested in what advantages people can identify to using this and seeing whether its worth me adopting this method.
If the only advantage is readability and its not being widely used then its counter productive as its only more readable to people who are familiar with the practice.
It makes it easier to do post-processing on the output, even if just inspection. That's possible with php's output buffering, but this is a more direct approach.
It's easier to reuse/repurpose code if output goes into a buffer instead of directly to the page. Again, built-in output-buffering can do some of this, but it's not as flexible.
Conceptually I think you can argue that a "single output" model is cleaner that something that urps out bits of html here and there, but as you note, it does come at a cost.
Of the top of my head: there's less likelihood for accidentally sending out headers. Clarification: you avoid the 'headers already sent' error caused by, e.g.
echo 'foo';
// … lots of other stuff
header('Location: /'); # or session_start() or set_cookie ....
echo 'bar';
Downside: the user's browser will start receiving data at a later point in time (in case of large sites).
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 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.