I am working on legacy code I have inherited and I have come across this code.
This Code works!
Ignore the variable names look at the { the first Condition opens but never closes the else has no open? it still works?
Is it continuing on both or only one condition and if one which one?
Why does it even work?
foreach($bla as $foo) {
if(condition) {
if(condition) {
// Do Something
}else
continue;
}
}
My assumption is that the inner condition will be using the else? but I am only assuming that because of this answer: Nested if-else behaviour without braces I cannot find a definitive answer for PHP
You may rephrase this code (with proper indentation usage):
foreach($bla as $foo) { // FOREACH
if(condition) { // IF#1
if(condition) { // IF#2
// Do Something
} else continue; // END IF#2
} // END IF#1
} // END FOREACH
Now answers on your questions:
Is it continuing on both or only one condition and if one which one?
It is continueing only if nested if() (IF#2) statement condition evaluated to false.
Why does it even work?
It works because if() allows syntax without brackets for simple operations. See example 1 at the manual. So nested if() closed exactly by continue operation with following delimiter ;.
Yes, the else applies to the inner condition. The code compiles because the else block has no opening brace, so the braces are still balanced. Here's the same code properly indented:
foreach($bla as $foo) {
if(condition) {
if(condition) {
// Do Something
}
else
continue;
}
}
Of course this is inconsistent and a very bad way to write this code.
Surely it means that if the first IF condition is true, it will then go to the second IF condition.
So the second IF condition will only be read if the first one is true.
foreach($bla as $foo) {
if(condition) {
if(condition) {
// Do Something
}else continue;
}
}
If the "else" (or if, for that matter) is a one-liner, it doesn't need braces. The "else" in question is continuing the inner "if".
Related
This question already has answers here:
What's the difference between if and elseif?
(8 answers)
Closed 6 years ago.
I have the following functions:
if(A==B)
{
//do stuff
}
if(C==B)
{
//do stuff
}
if(A==B)
{
//do stuff
}
else if(C==B)
{
//do stuff
}
What is the difference between these two? I get the meaning of it but I have seen programmers prefer the first one instead of the 2nd one? why?
I personally prefer the 2nd one.
That's mostly a question of preference. I saw many programmers using both cases regardless of the actual function.
But correctly use the first case if you want both conditions to be chekced absolutely, the second one as a nested condition.
In the first case, both will be executed which makes it slower than the second one, as it checks only for the elseif, if the if condition is false
$var = 1;
if($var+1 ==2)
{
echo "test1";
}
if($var-0==1)
{
echo "test2";
}
if($var+1==2)
{
echo "test1";
}
else if($var-0==1)
{
echo "test2";
}
will output
test1test2test1
so we see, that number 2 ignores the elseif, which makes it faster.
In the first condition both the statements are excecuted because they are independent to each other, so all of them will be tested.
if(A==B)
{
//do stuff
}
if(C==B)
{
//do stuff
}
In second else if is just a nested if inside an else, so only one will of them will be tested, either if or elseif
if(A==B)
{
//do stuff
}
else if(C==B)
{
//do stuff
}
Not the same.
else if (C==B) will not be executed (even if C equals B) if the first condition was true.
without "else", just if (C==B) will be executed even if the first condition was true (in that case A==C :)
If only one variable is equal and need to run the same code regardless, it is better to use the first code so there is no loss of performance. But if you need to run different code depending on your variable, then the second is better.
i'm reading a blog that give something php coding tips.there are two places I don't understand.
less/not use continue.
the structure :
do{
if(true) {
break;
}
if(true) {
break;
}
} while(false);
is better than :
if(true) {
} else if(true) {
} else {
}
can somebody explain why ?
I highly doubt this as a do { } while () is checked every iteration, whereas an if is just a simple comparison.
Maybe the point they were trying to demonstrate in the blog is that a do {} while() loop will pause your code until a condition is met, where as the if statements will be parsed and your code will continue regardless of whether the condition is met or not.
Why this is not possible to accomplish?
foreach($arr as $k => $v)
{
if($condition) { $obj->myMethod() && continue; }
}
After $obj->myMethod() gets evaluated then the keyword continue is evaluated (executed), resulting in skipping the current iteration.
EDIT: i'm asking this because something like:
if($error) { $log->fatal('Something weird happened.') && continue; }
is single line and self-explanatory.
continue is a statement not an expression.
And never the twain shall meet.
You can't put a statement in an expression. (What would echo false && continue; print?)
Instead, use an if, which can contain statements.
You cannot evaluate continue as a condition. The continue keyword does not work the same way as in other languages. In PHP, depending on context continue and break can be somewhat synonymous, consider this construct:
<?php
switch ($months)
{
// start with vowels
case 'august':
break;
case 'april':
continue; // exactly the same as "break" !!!
default:
return 'OK';
}
throw new StartsWithVowelException('Months with vowels are creepy');
?>
While we are on the topic, the break and continue keywords have a feature in PHP that make them a bit more interesting and powerful than their peers in other languages.
Both can be given a numerical argument when used in a loop that indicates how many loops to continue through or break out of. For example, here is an example that restarts the execution of an outer loop from within an inner one::
<?php
//
// verify that each sub array contains the given value
//
$lowerval = strtolower($value);
foreach ($TwoDArray as $otherArray)
{
foreach ($otherArray as $value)
{
if (strtolower($value) == $lowerval)
{
// we found the value -- this one definitely has it.
continue 2;
}
}
// if we've reached here, then the inner loop doesn't have the
// value. ¡aiiee!
}
?>
Hope this helps you out with these 2 constructs, good-luck.
continue is a statement. In PHP a statement and an expression are two different things, statements cannot be evaluated because they do not by nature return true or false which is a requirement for evaluation in PHP.
In PHP you'd have to do something like:
if(test()) continue;
for(;;)
{
if(!$monitor->Throttle($cause))
die('Fatal error: '.$monitor->error);
if($cause == THROTTLE_CAUSE_NONE)
break;
sleep(60);
}
i'm a beginner php developer. So how do you read the "for" syntax in previous code. is it valid ?
i got them from http://www.phpclasses.org/blog/post/132-Accelerate-Page-Accesses-Throttling-Background-Tasks-Unusual-Site-Speedup-Techniques-Part-2.html
for(;;) is a C idiom which means "do forever", an infinite loop. This loop will only exit when either the die statement fires (violently) , or the cause is set to THROTTLE_CAUSE_NONE (not so violently).
It's a for loop with no pre-setup, no condition and not post-iteration commands, effectively the same as while true (pseudo-code).
That's a forever-loop.
for(;;) is basically an infinite loop, nothing more :)
Ugh.
It is valid syntax, it creates an infinite loop. But it's ugly.
A much more beautiful way to do this would be
while ($cause = $monitor->Throttle($cause) != THROTTLE_CAUSE_NONE)
{
if(!$cause)
die('Fatal error: '.$monitor->error);
sleep(60);
}
It is valid. It creates an infinite loop, which in this case will be broken out of when/if the break statement executes, i.e. if($cause == THROTTLE_CAUSE_NONE)
The for loop has four parts:
for(initialization; exit condition; step) { body; }
Your loop has none of them, so without an exit condition it will just run forever until it hits the 'break' sentence:
if($cause == THROTTLE_CAUSE_NONE)
break;
An equivalent would be:
while(True) { ... }
Let's say I have this code:
if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith(md5($_POST[$foo['bar']]);
}
I could shorten that down by doing:
$value = md5($_POST[$foo['bar']];
if ($value == $somemd5) {
doSomethingWith($value);
}
But is there any pre-set variable that contains the first or second condition of the current if? Like for instance:
if (md5($_POST[$foo['bar']]) == $somemd5) {
doSomethingWith($if1);
}
May be a unnecessary way of doing it, but I'm just wondering.
No, but since the assignment itself is an expression, you can use the assignment as the conditional expression for the if statement.
if (($value = md5(..)) == $somemd5) { ... }
In general, though, you'll want to avoid embedding assignments into conditional expressions:
The code is denser and therefore harder to read, with more nested parentheses.
Mixing = and == in the same expression is just asking for them to get mixed up.
Since the if is just using the result of an expression, you can't access parts of it.
Just store the results of the functions in a variable, like you wrote in your second snippet.
IMHO your 2nd example (quoting below in case someone edits the question) is just ok. You can obscure the code with some tricks, but for me this is the best. In more complicated cases this advise may not apply.
$value = md5($_POST[foo['bar']];
if ($value) == $somemd5) {
doSomethingWith($value);
}