salir de if y foreach


Tengo un bucle foreach y una sentencia if. Si se encuentra una coincidencia que en última instancia, tengo que salir de la foreach.

foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;
        <break out of if and foreach here>
    }       
}
Author: Kaii, 2012-02-09

4 answers

if no es una estructura de bucle, por lo que no se puede "romper de ella".

Usted puede, sin embargo, salir de la foreach simplemente llamando a break. En su ejemplo, tiene el efecto deseado:

foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;

        // will leave the foreach loop and also the if statement
        break;
    }
    this_command_is_not_executed_after_a_match_is_found();
}

Solo para completar a otros que tropiezan con esta pregunta en busca de una respuesta..

break toma un argumento opcional, que define cuántas estructuras de bucle debe romper. Ejemplo:

foreach (array('1','2','3') as $a) {
    echo "$a ";
    foreach (array('3','2','1') as $b) {
        echo "$b ";
        if ($a == $b) { 
            break 2;  // this will break both foreach loops
        }
    }
    echo ". ";  // never reached
}
echo "!";

Resultante salida:

1 3 2 1 !


Si - por alguna oscura razón-quieres break de una instrucción if (que no es una estructura de bucle y por lo tanto no se puede romper por definición), simplemente puede envolver su if en una pequeña estructura de bucle para que pueda saltar fuera de ese bloque de código.

Tenga en cuenta que este es un hackeo total y normalmente no querría hacer esto:

do if ($foo)
{
  // Do something first...

  // Shall we continue with this block, or exit now?
  if ($abort === true) break;

  // Continue doing something...

} while (false);

El ejemplo anterior está tomado de un comentario en el PHP docs

Si te preguntas sobre la sintaxis: Funciona porque aquí se usa una sintaxis abreviada. Las llaves externas se pueden omitir porque la estructura del bucle contiene solo una instrucción: if ($foo) { .. }.

Otro ejemplo de esto:
do $i++; while ($i < 100) es equivalente a do { $i++; } while ($i < 100).

 506
Author: Kaii,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-10-04 19:52:10
foreach($equipxml as $equip) {
    $current_device = $equip->xpath("name");
    if ( $current_device[0] == $device ) {
        // found a match in the file            
        $nodeid = $equip->id;
        break;
    }
}

Simplemente use break. Eso lo hará.

 10
Author: Decent Dabbler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-02-09 17:22:30

Una forma más segura de acercarse a romper un bucle foreach o while en PHP es anidar una variable de contador incremental y if condicional dentro del bucle original. Esto le da un control más estricto que break; que puede causar estragos en otra parte en una página complicada.

Ejemplo:

// Setup a counter
$ImageCounter = 0;

// Increment through repeater fields
while ( condition ) 
  $ImageCounter++;

   // Only print the first while instance
   if ($ImageCounter == 1) {
    echo 'It worked just once';
   }

// Close while statement
endwhile;
 2
Author: staypuftman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 16:47:34

Para aquellos de ustedes que aterrizan aquí pero buscan cómo romper un bucle que contiene una instrucción include, use return en lugar de break o continue.

<?php

for ($i=0; $i < 100; $i++) { 
    if (i%2 == 0) {
        include(do_this_for_even.php);
    }
    else {
        include(do_this_for_odd.php);
    }
}

?>

Si desea romper al estar dentro de do_this_for_even.php necesitas usar return. Usar break o continue devolverá este error: Cannot break / continue 1 nivel. He encontrado más detalles aquí

 0
Author: Nick Constantine,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-12 15:50:03