note 40858 deleted from control-structures.break by felipe

From: Date: Tue, 29 Jan 2008 11:26:40 +0000
Subject: note 40858 deleted from control-structures.break by felipe
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-135528@lists.php.net to get a copy of this message
Note Submitter: 2et at free dot fr ---- If you need to execute a sequence of operations, where each step can generate an error, which you want to interrupt the sequence and you don't want to have an incrementing if...then...else/elseif indenting like this: <?php // Level 0 indenting. $query = "SELECT myAttr FROM myTable"; $db = DB::connect($dbUrl); if (DB::isError($db)) { // Level 1 indenting. echo "Error: Connection failed.<br/>"; } else { $dbResult = $db->query($query); if (DB::isError($dbResult)) { // Level 2 indenting. echo "Error: Query failed.<br/>"; } else { // ... } } ?> First, elseif can be used to prevent indent level increase by replacing: <?php -- } else { $dbResult = $db->query($query); if (DB::isError($dbResult)) { // Level 2 indenting. -- by -- } elseif (DB::isError($dbResult = $db->query($query))) { // Level 1 indenting SUCCESS! -- ?> However, it's not possible every time, because you can't reasonably put everything between the else and the if keywords in the if condition like above. Therefore, I suggest the following little trick using while and break: <?php while(1) { // Level 1 indenting. $query = "SELECT myAttr FROM myTable"; $db = DB::connect($dbUrl); if (DB::isError($db)) { // Level 2 indenting. echo "Error: Connection failed.<br/>"; // Exit sequence. break; } // Back to level 1. $dbResult = $db->query($query); if (DB::isError($dbResult)) { // Level 2 indenting. echo "Error: Query failed.<br/>"; // Exit sequence. break; } // Back to level 1. // ... // Quit while. break; } ?> Using do { ... } while(0) is even better, because the last break keyword can be removed. Note: If you intend to use other statements using break (while, switch, for, foreach...) in the while(1) { ... } statement (or do while...), you can still exit using break's argument: <?php while (1) { while(cond) { if (error) { break 2; } } } ?>

« previous php.notes (#135528) next »