note 40858 added to control-structures.break
| From: | 2et at free dot fr | Date: | Wed, 17 Mar 2004 10:48:42 +0000 |
| Subject: | note 40858 added to control-structures.break | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-66951@lists.php.net to get a copy of this message | ||
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;
}
}
}
?>
----
Manual Page -- http://www.php.net/manual/en/control-structures.break.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+40858
Delete -- http://master.php.net/manage/user-notes.php?action=delete+40858&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+40858&report=yes
Search -- http://master.php.net/manage/user-notes.php