简体   繁体   中英

skipping if statement if condition met and continue executing the code below php

I will try to explain what I want to achieve with commented code.

what I am trying to do is skip through if statement if the condition is met and continue executing the code outside conditional statement.

<?php
  if (i>4) {
    //if this condition met skip other if statements and move on
  }

  if (i>7) {
    //skip this
?>

<?php
  move here and execute the code
?>

I know about the break, continue, end and return statement but that is not working in my case.

I hope this clears my question.

If your first condition met and you want to skip other condition you can use any flag variable as below :

<?php
        $flag=0;
        if (i>4)
        {
          $flag=1;
        //if this condition met skip other if statements and move on
        }

        if (i>7 && flag==0)
        {
        //skip this
        ?>

        <?php
        move here and execute the code
        ?>

You can use a goto

<?php
if (i>4)
{
//if this condition met skip other if statements and move on
goto bottom;
}

if (i>7)
{
//skip this
?>

<?php
bottom:
// move here and execute the code
// }
?>

But then again, lookout for dinosaurs.

转到 xkcd

Use if-elseif-else :

if( $i > 4 ) {
    // If this condition is met, this code will be executed,
    //   but any other else/elseif blocks will not.
} elseif( $i > 7 ) {
    // If the first condition is true, this one will be skipped.
    // If the first condition is false but this one is true,
    //   then this code will be executed.
} else {
    // This will be executed if none of the conditions are true.
}

Structurally, this should be what you're looking for. Try to avoid anything that will lead to spaghetti code like goto , break , or continue .

On a side note, your conditions don't really make much sense. If $i is not greater than 4, it will never be greater than 7, so the second block would never be executed.

I typically set some sort of marker, such as:

<?php
    if (i>4)
    {
    //if this condition met skip other if statements and move on
    $skip=1;
    }

    if (i>7 && !$skip)
    {
    //skip this
    ?>

    <?php
    move here and execute the code
    ?>
<?php
  while(true)
  {
    if (i>4)
    {
    //if this condition met skip other if statements and move on
    break;
    }

    if (i>7)
    {
    //this will be skipped
    }
  }    
?>

    <?php
    move here and execute the code
    ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM