note 14301 deleted from control-structures.switch by crell

From: Date: Wed, 29 Jun 2022 17:51:57 +0000
Subject: note 14301 deleted from control-structures.switch by crell
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-218664@lists.php.net to get a copy of this message
Note Submitter: x@x ---- often you will have to perform multiple actions in sequence, but this sequence must be broken once one of them detects a stop condition (such as an error, when validating form request variables). One way is to use: if (check1() && check2() && check3() ) valid(); else error(); But when the sequence is long and must reordered, this can be errorprone because not all line of check have the same syntax (imagine that you want to comment one of them). Another way is to rewrite it as: check1() and check2() and check3() and ... valid() or error(); The above syntax does not fit well when the valid() code must be several statements. An alternative syntax can be: switch (false) { case check1(): case check2(): case check3(): error(); break; default: valid(); } This last equivalent sample show you that each case expressions is evaluated, until one of them evaluates to a value equal (==) to the switch expression. Above, the error() code will only be called if one of the check evaluates to false. And the valid() code will only be evaluated only if the switch reach the default, which means that none of the above check returned false...

« previous php.notes (#218664) next »