MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

break

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.

<?php
$arr
= array ('one', 'two', 'three', 'four', 'stop', 'five');
while (list (,
$val) = each ($arr)) {
   if (
$val == 'stop') {
       break;   
/* You could also write 'break 1;' here. */
  
}
   echo
"$val<br>\n";
}

/* Using the optional argument. */

$i = 0;
while (++
$i) {
   switch (
$i) {
   case
5:
       echo
"At 5<br>\n";
       break
1/* Exit only the switch. */
  
case 10:
       echo
"Al 10; saliendo<br>\n";
       break
2/* Exit the switch and the while. */
  
default:
       break;
   }
}
?>



add a note add a note User Contributed Notes
break
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}) {
      
// Arbitrary code here--the details aren't important
      
case 'i': // increment
          
echo ++$num." ";
           break;
       case
'f': // find factors
          
for ($factor = 1; $factor <= $num; ++$factor) {
               if (
$num % $factor == 0) {
                   echo
"[".$factor."] ";
                  
// stop processing file if 7 is a factor
                  
if ($factor == 7)
                       break
3; // break out of while loop
              
}
           }
   }
}
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}) {
          
// Arbitrary code here--the details aren't important
          
case 'i': // increment
              
echo ++$num." ";
               break;
           case
'f': // find factors
              
for ($factor = 1; $factor <= $num; ++$factor) {
                   if (
$num % $factor == 0) {
                       echo
"[".$factor."] ";
                      
// stop processing file if 7 is a factor
                      
if ($factor == 7)
                           break
3; // break out of while loop
                  
}
               }
       }
   }
}
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 {
  
// some code
  
if ($condition)
       break;
  
// some more code
} while (FALSE);
?>
or
<?php
switch ($dummy) {
   default:
      
// some code
      
if ($condition)
           break;
      
// some more code
}
?>
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
// 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;
       }
   }
}
?>
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':
          
//Processing code
    
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

Ilusiones Opticas
ilusion_optica_044.jpg
Contenidos Web

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

Humor Gráfico
humor_grafico_058.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake 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 WebRainbow 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 FortunaMahjongg 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 2Chainz 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.
DeliciousDelicious
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!
BookwormBookworm
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!
ZumaZuma
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 AtlantisJewel 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 QuestJewel 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 2Bejeweled 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.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0175.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail

Warning: array_rand(): First argument has to be an array in /var/www/html/contenidos/efemerides.php on line 14
Sucedió el...

31 de agosto de

Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid fallera mayor campus party alcacer feria valencia fernando alonso loterias dinero inversiones violencia de genero makro empresas cartera soledad tolerancia metro valencia gobierno de españa violencia de genero UIMP navidad