I have 4 IF sentences, after that i want to say else(not the condition of any of if) but i get an error.
I have:
if (condition 1) { }
if (condition 2) { }
if (condition 3) { }
if (condition 4) { }
el开发者_如何学运维se { }
What am i doing wrong ?
if the condition is on the same variable
use switch case
its more clear !
http://php.net/manual/en/control-structures.switch.php
else see Mark Baker answer
if (condition 1) {
...
} elseif (condition 2) {
...
} elseif (condition 3) {
...
} elseif (condition 4) {
...
} else {
...
}
EDIT
The difference is that each of your "if (condition n) { }" statements (except the last) is syntactically complete, terminating with the closing } and therefore your "else { }" is only related to the very last if statement in your list.
if (condition 1) { // Test if condition 1 is met
...
} // end of if (condition 1) statement
if (condition 2) { // Test if condition 2 is met regardless of any previous conditions
...
} // end of if (condition 2) statement
if (condition 3) { // Test if condition 3 is met regardless of any previous conditions
...
} // end of if (condition 3) statement
if (condition 4) { // Test if condition 4 is met regardless of any previous conditions
...
} else { // will always be executed if (condition 4) is not met, even if conditions 1,2 or 3 have been met
...
} // end of if (condition 4) statement
So if condition 1 is met, the code will still check for conditions 2 and 3, then test for condition 4 and execute the else if condition 4 is not met, ecen though condition 1 was met.
Using elseif, the else will only be executed if none of conditions 1, 2, 3 or 4 or met.
IF the conditions are simple id use switch/case:
switch (true) {
case /* condition 1 */:
//logic
break;
case /* condition 2 */:
//logic
break;
case /* condition 3 */:
//logic
break;
case /* condition 4 */:
//logic
break;
default:
// essentially your else logic
}
IF your conditions are complext then use elseif
as others have mentioned.
How about this:
if (condition 1) { } else if (condition 2) { } else if (condition 3) { } else if (condition 4) { } else { }
or this:
if (condition 1) { }; if (condition 2) { }; if (condition 3) { }; if (condition 4) { } else { }
Depending on what you want :)
i think a switch case pretty much covers the whole thing:
switch($something)
{
case "val1": do_something();
break;
default: do_something_else();
}
greetings
精彩评论