note 61260 deleted from language.control-structures by bjori
| From: | bjori@php.net | Date: | Wed, 26 Apr 2006 15:40:36 +0000 |
| Subject: | note 61260 deleted from language.control-structures by bjori | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-109754@lists.php.net to get a copy of this message | ||
Note Submitter: Andrzej dot Martynowicz at gmail dot com
----
Have you ever encountered the situation when wanted to break processing the if statement before
final '}' bracket?
Usually you need to use nested if statemets, which can be sometimes very confusing:
<?
if( $initial_condition ) {
if( $condition_1 ) {
// do something that leeds to next condition
if( $condition_2 ) {
// and even more confusing situation
if( $condition_3 && $condition_4 ) {
// code that satisfies $condition_3 as well as $condition_4
} elseif( $condition_4 ) {
// code that satisfies $condition_4 but not $condition_3
}
}
}
}
?>
The trick, that I came up with, is to put the "switch" statement after the "if"
condition (it will be executed always when $initial_condition of the "if" gives positive
result). Than one can open the block of code for this "switch" statement as if it was a
block for "if". The "switch" statement should be written with only one
"case" - "default" case, so that code within "switch" will be executed
independently of the condition of the "switch" (so one can put there just anything.. i
usually use the $fake variable as shown below). Now because the block of code belongs to
"switch" (not to "if"), can be broken by "break" whenever programmer
want to (and in fact it will break processing of the "if" statement). See below how this
works:
<?
$fake = '';
if( $initial_condition ) switch( $fake ) { default: // switch statement trick
if(! $condition_1 ) break;
// do something
if(! $condition_2 ) break;
// code is no more confusing
// following statements looks good now
if( $condition_3 && $condition_4 ) {
// code that satisfies $condtion_3 as well as $condition_4
} elseif( $condition_4 ) {
// code that satisfies $condtion_4 but not $condition_3
}
// hovever it could be rewriten in even more readable way
if(! $condition_4 ) break;
if( $condition_3 ) {
// code that satisfies $condition_3 as well as $condition_4
} else {
// code that satisfies $condition_4 but not $condition_3
}
}
?>