Jump to content

[SOLVED] Break out of an if?


Azu

Recommended Posts

Hi, can somebody please tell me which command I should use to break out of an if(){blah blah}?

 

In a while(){blah blah} I would use "break;" but that doesn't seem to work in an if(){blah blah}.

 

I know that I could just put all of the rest of the if in {} and use if false so that it will only do the rest of the if if the condition isn't meant, but that is very sloppy and ugly and I really just want to know a function to just break out of the if(){} please..

Link to comment
Share on other sites

Because I have this big if(){} thing and half-way through it, if a certain condition is met/not met, then it should not run the rest of the if. I was just wandering if there is an elegant way to break out of it, instead of putting the whole rest of the if(){} inside of yet ANOTHER if(){}.. o_o

Link to comment
Share on other sites

If you mean you want to do something like this (just an example):

 

$i = 0;
while($i < 10) {
if($i % 2 == 0) {
echo "even!";
}
else {
echo "odd";
}
}

 

You could also do it like....

$i = 0;
while($i < 10) {
if($i % 2 == 0) {
echo "even!";
continue;
}
echo "odd!";
}

Link to comment
Share on other sites

There's a cute trick I've used to work around php's lack of goto:

 

while (an if condition) {
  blah
  blah
  if (some condition) {
    break; # goto end
  }
  blah
  if (some other condition) {
    break; # goto end
  }
  blah
  break; # finish while loop
} # This is "end"

 

Dijkstra is rolling in his grave I'm sure.. but seriously, a well considered use of goto can make code clearer.

 

Basically it's an "if" but I turned it into a "while", so I can break out of it.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.