skip to Main Content

i tried to make the loop stop and only print 1 content inside their if, if the condition have been met but it always either print the condition more than one, have both condition printed, or the else statement doesn’t display anything. Any suggestion?

$tf = 'belom';
$tf2 = 'belom';
if ($tf == 'belom') {
               foreach ($roles as $role) {
                    if (in_array("user", $role) && $tf == 'belom') {
                         print_r($role);
                         $tf = 'udah';
                         echo '<button type="button" class="btn btn-primary" >Primary</button>';
                         $tf2 = 'udah';
                    }elseif ($tf2 !== 'udah') {

                         echo '<button type="button" class="btn btn-primary" disabled>Primary</button>';
                         $tf2 = 'udah';
                    }
               }
          } 
     // }

Sorry for the grammar, i’m not really good with english.
Hope you guys understand.

3

Answers


  1. Use break to end the execution of the foreach.

    Login or Signup to reply.
  2. Read the documentation for break keyword. You can use as below.

    $tf = 'belom';
    $tf2 = 'belom';
    if ($tf == 'belom') 
    {
       foreach ($roles as $role) 
       {
         if (in_array("user", $role) && $tf == 'belom') 
         {
            print_r($role);
            $tf = 'udah';
            echo '<button type="button" class="btn btn-primary" >Primary</button>';
            $tf2 = 'udah';
            break; // USE THIS KEYWORD TO BREAK OUT FROM THE LOOP
         }
         elseif ($tf2 !== 'udah') 
         {
            echo '<button type="button" class="btn btn-primary" disabled>Primary</button>';
            $tf2 = 'udah';
            break; // USE THIS KEYWORD TO BREAK OUT FROM THE LOOP
         }
       }
    }
    
    Login or Signup to reply.
  3. <?php
    foreach($array as $value){
     if($value === 'stop looping entirely'){
      break;
     }
     else if($value === 'skip the current iteration'){
      continue;
     }
    }
    ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search