if condition best practice [duplicate] - php

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.

Related

Is there any way to break if operator like as while [duplicate]

This question already has answers here:
Any way to break if statement in PHP?
(21 answers)
Closed 8 years ago.
Is there any way to break an if statement like a while loop?
while(true) {
break;
}
if(true) {
//break if
} else {
//continue execution here or miss if at all
}
Yes, using goto. Use with caution, as it's usually an indication of bad code habits elsewhere. It does have legitimate uses though (like breaking out of nested loops).
http://php.net/manual/en/control-structures.goto.php
I think your question is poorly-worded. I think this is the problem you're having:
if( foo ) {
if( bar ) {
baz();
} else {
qux();
}
} else {
qux();
}
You want to simplify this so that qux() need only be expressed once, rather than twice. A possible solution using goto exists:
if( foo ) {
if( bar ) {
baz();
} else {
goto quxLabel;
}
} else {
quxLabel:
qux();
}
This works, but I think a better solution (if possible in your case) is to compose your branch conditions. This requires that you be able to evaluate bar independently of foo, so I don't know if this applies in your case:
if( foo && bar ) baz();
else qux();
If bar depends on foo then you can still use this technique, but take advantage of the short-circuiting behaviour of the && operator:
if( foo && computeBar( foo ) ) baz();
else qux();
Simply, inverse the order and use !:
<?php
if(!true){
echo "execution here or miss if at all";
} else {
echo "Nothing";
}
View this DEMO: http://codepad.org/XdFKfY9R
The if-statement is used to branch code without repetition so there is no need for a break constructor. It's a different thing when you are using loop control statements, especially those without a given loop condition statement like:
while (1==1) {
...
}
To avoid endless loops you will need to combine branch and loop statements, perhaps that was the idea behind your question:
while (1==1) {
// do stuff
...
// special condition
if ($cancel) {
break;
}
}
if(true){
goto end;
}
else {
continue execution here or miss if at all
}
end:
/* your statement*/
try {
if (...) {
do_something();
...
throw new \Exception(); // Break here
...
}
} catch (\Exception $e) {}
// Resumes here:
do_something_now()
Using Exceptions is generally the best way to break out of loops (or anything else). They are used to indicate an error, but can be caught and handled wherever you like.

PHP nested else statement without braces

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".

why those two points are php tips?

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.

PHP Nested Ifs vs Single If with Multiple Conditions [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
php multiple if conditions
What is better ? Multiple if statements, or one if with multiple conditions
So I was working on a segment of code in which I ended up using two different styles of if statements. That got me wondering - which one is more efficient in PHP? Are there times when one might be better than the other, despite general differences (if present)? Is there a certain level of complexity where the benefits become clear (if close) or close (if originally clear)? Also, are there other benefits of one method over the other, other than aesthetic or subjective differences?
if ($value == 'someval') {
if($otherval == 'someval') {
// do stuff
} else if ($otherval == 'otherval') {
// do same stuff
}
}
vs
if (($value == 'someval') && ($otherval == 'someval' || $thirdval == 'someval') {
// do stuff
}
Note - I don't care what works for C# or Java or whatever other language, unless someone can show that they handle the construct exactly the same.
So long as you're executing the same code in each block (as you've indicated by your comments) then they'll both do the trick (and no, there's really not much of a performance difference).
However, typically it's not the case that you'd execute the same code both ways, so logically the first block is actually different from the second in that case. Here's an example:
if($value == 'someval') {
if($otherval == 'someval') {
doSomething();
}
else if ($otherval == 'otherval') {
doSomethingElse();
}
}
versus:
if(($value == 'someval') && ($otherval == 'someval' || $otherval == 'otherval')) {
//we now still need to evaluate $otherval in order to determine which func to execute...
//this adds bloat...
if($otherval == 'someval') {
doSomething();
}
else if ($otherval == 'otherval') {
doSomethingElse();
}
}
So as you can see in the case above the second block is actually less efficient than the first.
There is no real difference, you should use whichever is more readable.
Nested or not nested if-blocks?

If first argument falls true in a condition with and operators will the next run?

Lets say I've got a pice of code that looks like this:
if( !isset($this->domainID) && !$this->getDomainID() ){
return false;
}
Will the 2nd statement run if the first one is true?
Because performance wise it would be stupid to get the ID from the database if I've already got it and there's a lot of other situation where the same apply. If it doesn't I'd have to nest them, am I right?
I don't know if there's an standard on how programming language work in these cases or if it's different in other languages then php. I tried googling it but I didn't really know what to search for in this case. As you can see I hade a quite hard time describing it in the title.
Yes. If the first is true, the second will be evaluated. Conversely, if the first is false, the second will not be evaluated. This can be a good place for micro optimizations and, as you noted, logical progression.
Per the comments, the inverse is true for OR conditions. So if the first expression is false the next will be evaluated and if the first expression is true the next will not.
No, if the first is false, the second will not be evaluated.
What you're really talking about here is "lazy evaluation". It's often used in functional programming languages and can vastly improve the run-time. See here for more info: http://en.wikipedia.org/wiki/Lazy_evaluation
PHP does not use lazy evaluation but in conditionals like this it does at least stop before the second argument if the result is already clear.
Answer is yes, you can see it by yourself by doing something like this:
#!/usr/bin/php
<?PHP
function test1() {
echo "inside test1\n";
return false;
}
function test2() {
echo "inside test2\n";
return true;
}
echo "test1 first AND test2 second\n";
if (test1() && test2()) {
echo "both passed\n";
}
echo "test2 first AND test1 second\n";
if (test2() && test1()) {
echo "both passed\n";
}
echo "test1 first OR test2 second\n";
if (test1() || test2()) {
echo "one passed\n";
}
echo "test2 first OR test1 second\n";
if (test2() || test1()) {
echo "one passed\n";
}
?>
Yes, you are using an AND so both conditions will be checked if the first is true (but not if the first is false).
If you had used an OR and the first condition was true, php wouldn't evaluate the second.

Categories