Works for a Living
Works for a Living

Reputation: 1293

While Loop not Breaking when Condition is Met

I've got several working while loops in my function but this one I just can't get to work as it's supposed to. I assumed that while($variable == false) would break out of the loop as soon as $variable = true; occurs. Here's a bare bones version, with only two statements inside the loop.

$excluded = false;
while($excluded == false):
    $excluded = in_array(strtolower($extension), $GLOBALS['codexts']) ? true : false;
    $excluded = $file != "." && $file != ".." ? false : true; 
    break;
endwhile;

Inside the loop, the first definition does produce false when it's suppose to, but the loop doesn't break. It goes on to the second one, which returns true. If I change the second one to this:

$excluded = $excluded ? $excluded : ($file != "." && $file != ".." ? false : true); 

...then I get the result I want, but only because I'm correcting for the failure of the while loop to break when $excluded is first defined as true. What am I doing wrongly here?

UPDATE I just reread the manual, and apparently I missed this part:

The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration

That's why the iterations were reverting back to false. I do need to do manual conditional breaks after all.

Upvotes: 3

Views: 3999

Answers (2)

Sajad Karuthedath
Sajad Karuthedath

Reputation: 15767

try

$excluded = false;
while($excluded == false) {
   $excluded = in_array(strtolower($extension), $GLOBALS['codexts']) ? true : false;
   if ($excluded == true) {
     break;
   }
    $excluded = $file != "." && $file != ".." ? false : true; 
    break;
} 
?>

Upvotes: 3

paulsm4
paulsm4

Reputation: 121609

Q: Why don't use use conventional syntax?

Q: Why a redundant "break"?

Q: Why are you setting the expression twice before testing, and do you really need "?:" here? Twice???

Q: Can't you simplify the expression that changes your flag (changes "$excluded")?

SUGGESTION:

$myvar = false;
while(!$myvar) {
  $myvar = << something that sets/clears my flag >>
}

Upvotes: 0

Related Questions