|
|
 |
break escapa de la estructuras de control
iterante (bucle) actuales for,
while, o switch.
break accepta un parámetro opcional, el cual determina
cuantas estructuras de control hay que escapar.
traxer at gmx dot net
30-Dec-2005 06:53
vlad at vlad dot neosurge dot net wrote on 04-Jan-2003 04:21
> Just an insignificant side not: Like in C/C++, it's not
> necessary to break out of the default part of a switch
> statement in PHP.
It's not necessary to break out of any case of a switch statement in PHP, but if you want only one case to be executed, you have do break out of it (even out of the default case).
Consider this:
<?php
$a = 'Apple';
switch ($a) {
default:
echo '$a is not an orange<br>';
case 'Orange':
echo '$a is an orange';
}
?>
This prints (in PHP 5.0.4 on MS-Windows):
$a is not an orange
$a is an orange
Note that the PHP documentation does not state the default part must be the last case statement.
develop at jjkiers dot nl
13-Jul-2005 02:06
To php_manual at pfiff-media dot de:
This is only possible with PHP5, because <PHP5 doesn't have a proper exception infrastructure.
php_manual at pfiff-media dot de
13-Mar-2005 06:21
instead of using the while (1) loop with break like suggested in an earlier note, I would rather recommend throwing an exception, e.g.:
<?php
try {
$query = "SELECT myAttr FROM myTable";
$db = DB::connect($dbUrl);
if (DB::isError($db)) {
throw new Exception("Connection failed");
}
} catch (Exception $e) {
echo "Error: ".$e->getMessage()."</br>";
}
?>
Ilene Jones
21-Feb-2005 01:08
For Perl or C programmers...
break is equivelant to last
while(false ! == ($site = $d->read()) ) {
if ($site === 'this') {
break; // in perl this could be last;
}
}
abodeman at yahoo
17-May-2004 11:28
The use of "break n" to break out of n enclosing blocks is generally a pretty dangerous idea. Consider the following.
Let's say you have a text file that contains some lines of text, as most text files do. Let's also say that you are writing a little piece of PHP to parse each line and interpret it as a string of commands. You might first write some test code just to interpret the first character of each line, like this:
<?php
$num = 0;
$file = fopen("input.txt", "r");
while (!feof($file)) {
$line = fgets($file, 80);
switch ($line{0}) {
case 'i': echo ++$num." ";
break;
case 'f': for ($factor = 1; $factor <= $num; ++$factor) {
if ($num % $factor == 0) {
echo "[".$factor."] ";
if ($factor == 7)
break 3; }
}
}
}
fclose($file);
?>
So, now that you have this magnificent piece of test code written and working, you would want to make it parse all the characters in each line. All you have to do is put a loop around the switch statement, like so:
<?php
$num = 0;
$file = fopen("input.txt", "r");
while (!feof($file)) {
$line = fgets($file, 80);
for ($i = 0; $i < strlen($line); ++$i) {
switch ($line{$i}) {
case 'i': echo ++$num." ";
break;
case 'f': for ($factor = 1; $factor <= $num; ++$factor) {
if ($num % $factor == 0) {
echo "[".$factor."] ";
if ($factor == 7)
break 3; }
}
}
}
}
fclose($file);
?>
(Of course, you changed "$line{0}" to "$line{$i}", since you need to loop over all the characters in the line.)
So now you go and try it out, and it doesn't work. After a bunch of testing, you discover that when 7 is a factor, the code stops processing the current line, but continues to process the remaining lines in the file. What happened?
The problem is the "break 3;". Since we added another loop, this doesn't break out of the same loop it did before. In a small program like this, it's not too difficult to find this problem and fix it, but imagine what it would be like if you have thousands of lines of PHP with a numbered break statement hidden in the mess somewhere. Not only do you have to find it, you also have to figure out how many layers you want to break out of.
Unfortunately, PHP doesn't really offer any alternative to numbered break statements. Without line labels, there's no way to refer to a specific loop. There is also no "goto" statement in PHP. You could kludge your way around things with something like
<?php
do {
if ($condition)
break;
} while (FALSE);
?>
or
<?php
switch ($dummy) {
default:
if ($condition)
break;
}
?>
but these sorts of tricks quickly add an enormous amount of clutter to your code.
Thus, the moral of the story is simply to be very careful when using numbered break statements. The numbered break statement is one of the few language features that can break silently when other code is changed.
2et at free dot fr
17-Mar-2004 05:48
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
$query = "SELECT myAttr FROM myTable";
$db = DB::connect($dbUrl);
if (DB::isError($db)) {
echo "Error: Connection failed.<br/>";
} else {
$dbResult = $db->query($query);
if (DB::isError($dbResult)) {
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)) {
--
by
--
} elseif (DB::isError($dbResult = $db->query($query))) {
--
?>
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) {
$query = "SELECT myAttr FROM myTable";
$db = DB::connect($dbUrl);
if (DB::isError($db)) {
echo "Error: Connection failed.<br/>";
break;
}
$dbResult = $db->query($query);
if (DB::isError($dbResult)) {
echo "Error: Query failed.<br/>";
break;
}
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;
}
}
}
?>
jody at redstarmedia dot org
04-Mar-2004 08:06
If you are careful about repeating code when using multiple cases that pretty much do the same thing, you can use multiple cases for one block of code / one break. Below is an example.
<?php
switch($var)
{
case 'foo':
case 'bar':
break;
}
?>
vlad at vlad dot neosurge dot net
04-Jan-2003 01:21
Just an insignificant side not: Like in C/C++, it's not necessary to break out of the default part of a switch statement in PHP.
| |
| | Citas célebres | Si mi película ha hecho desgraciado a alguien más, habré hecho bien mi trabajo. Woody Allen Cineasta estadounidense (n. 1953) | | Citas en tu mail | | ©Contenidos Gratis |
| Chiste de... Médicos | | Historias octogenarias | - ¿Así que tu abuelo murió en la consulta del médico? ¿Y el médico qué le dijo antes de que muriera?
- "Cuente conmigo, señor: cinco, cuatro, tres, dos, uno, cero..." | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|