what is the difference between these two foreach loops? - php

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.

Related

PHP bracket less IF condition not accepting more than one statement

I've never been a fan of brackets in control structures and only today I realised how it only accepts one statement within a bracket less if condition, if I have more than one statement it will throw a syntax error. Is this how PHP works or can it be something wrong with my IDE?
Obviously the error is clear but I just want to make sure this is normal.
If you have any other any links to other alternate syntax let me know please.
Bellow is just something I pasted from a project am doing and example of the syntax error.
if($this->reel3 = 1)
parent::addCash($this->$bet*2);
print(parent::getCash()); // < Line throwing the syntax error
else
// TODO
EDIT (FURTHERMORE)
After looking at some of the answer and comments I was wondering how its done in a professional environment, I know this is more about taste but I want to know from the professional out there if the style of the syntax matters?
Would
if(condition)
{
//something
} else {
//something
}
be better than
if(condition):
//something
else:
//something
endif;
or any other way of writing the same piece of code?
This is how php works. If you don't put brackets around your if statement only the next statement is in the if block all other follow up statements are outside of it. But since you have a else block after it you will get a error.
(BTW: You make an assignment in the if block, so this will be always true)
Look at these 2 examples:
if($this->reel3 = 1)
parent::addCash($this->$bet*2); //In the if statement
print(parent::getCash()); //Outside the if statement
else
Same as:
if($this->reel3 = 1) {
parent::addCash($this->$bet*2);
}
print(parent::getCash());
//^^^^^ I think here it's more clear to see that this will give you a error, since it's between the if and else block which is not allowed
else { }
For more information about the control structure if see the manual: http://php.net/manual/en/control-structures.if.php
Take a look at the answer of this question:
PHP conditionals, brackets needed?
And yes, it is PHP, not your IDE!
This is perfectly normal of all programming languages that use brackets rather than indentation to designate blocks of code. Without the brackets, there is no way for the interpreter to know which lines are part of the if block and which aren't. The one-line if-block is a convenient shortcut: if you don't include any brackets, PHP like many other languages will treat the single line directly following the if statement as the body of the if block.
Note PHP does have an alternative syntax for if statements as well, using colons instead of brackets, but that's a story for another day.

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.

Any reason why someone would use printf() for pretty much everything?

I am taking over a project from an existing programmer who, to be honest, left the project in a massive heap of unmaintainable, unreadable mess (edit/clarification: dozens upon dozens of standalone .php pages that are a soup of php/html/css that all reference one giant 1500 line 'functions.php' file, ack)
That being said, it seems that pretty much everywhere there is a variable, array, etc. he used printf().
For example, instead of using:
foreach($thing as $t) {
echo "<option value='".$t."'>".$t."</option>";
}
He would use something like:
foreach($thing as $t) {
printf("<option value='%s'>%s</option>", $t, $t);
}
Does anyone have any insight as to why exactly he would do this? Is there some unknown benefit that I am not aware of by using printf() instead of echo/print?
Please note that this isn't just for values that might need to be validated/scrubbed, but for EVERYTHING. Data pulled from the database, random variables and arrays that were defined elsewhere, absolutely everything is printf() instead of just echo or print, and i'm trying to figure out why he would use this method as it might help me understand the logic behind some of the things he built.
"The only reason to use printf() in preference over echo or print() is if you will be using the format string place-holders feature with additional arguments (one for each such place-holder). If not, then print() will be faster, and echo even (very slightly) faster since it does not generate a return value."
Found here: echo VS printf
I imagine he did it for code read-ability. I think using printf/sprintf is more readable than
embedding variables directly into string and alternating '"""''""''".
Personally I think this is the most readable method:
<?php foreach($thing as $t): ?>
<option value="<?php echo $t ?>"><?php echo $t ?></option>
<?php endforeach; ?>
It has the added benefit of looking nice in most IDEs
Well i would have definitely used printf in your example. I often use printf, sprintf, or strtr when outputting html elements with a lot of attributes or complex ones. Its just more readable and its much easier to swap out the values later.

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. :)

PHP Alternative Control Structures, any drawbacks?

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

Categories