2

How can I break while loop and for loop too when while loop is true?

<?php
for($i=0; $i<4; $i++){
    $result = mysql_query("SELECT * FROM table WHERE weight='$i'");
    while($row = mysql_fetch_array($result)){
        echo $row['cell'];
        break; //I need to break the while loop and the for loop too in this line exactly, when he find and echo the "cell"!
    }
}
?>
3
  • 1
    Wouldn't specifying break 2; work? See: php.net/manual/en/control-structures.break.php Commented Jan 23, 2014 at 4:21
  • 1
    Why do you need the outer loop then? Why don't you just hardcode $i = 0; ? Commented Jan 23, 2014 at 4:21
  • 1
    Read the Docs.. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.... its in here:: php.net/manual/en/control-structures.break.php Commented Jan 23, 2014 at 4:21

4 Answers 4

9

It is

break 2;

References:

...

Sign up to request clarification or add additional context in comments.

Comments

1

Use Flags:

One flag inside while : Set this flag to 1 when you break while

One flag in outer for loop: If while loop flag is set then break for loop

Comments

1

Instead of doing a break why not do the following

SELECT * FROM table WHERE weight BETWEEN 0 AND 3

OR just

SELECT * FROM table WHERE weight = 0

You would be limiting querying the database multiple times and probably takes less time but you'd wouldn't notice it with a query like this.

Not sure why you there is a for loop then break on first iteration when you can just query the database and echo something. Unless OP has other plans for this code and reduced the code for SO the loop is really unnecessary.

Comments

0

use exit instead of break.

break results exit from current iteration while exit results exit from overall pgm.

3 Comments

So why would OP prefer exit over break?
in this case exit results exit from both while and for loop.
it does. But it stops the whole application, which is not the case. At least it's not obvious that it's what OP wants

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.