1

When I execute this code:

$result = mysql_query("SELECT * FROM example_table");

$i = 0;
while ($row = mysql_fetch_array($result))
{
    for ($j = 0; $j < $c; $j++)
    {
        if ($db_array[$j]['ID'] == $row['id'])
        {
            $del_counter = 0;
            break 2;
        }
        else
        $del_counter = 1;
    }

    if ($del_counter == 1)
    {
    $del_array[$i] = $row['id'];
    $i++;
    }

}

This does not break the two level looping. Instead, the $del_array stores all the row ids. I need to compare db_array[][id] with the array "row" (fetched from the database). And need to check which elements of db_array are deleted from the database. So, what I did is I tried to store the ids of deleted items in an array. But the break does not work. Am I missing something?

Thanks in anticipation.

BG

7
  • try to define $del_counter=0 just before the nested for. Commented Sep 28, 2011 at 8:44
  • 1
    I don't want to sound rude, but break 2 will work as announced, so I would assume you have a logic flaw in your code. Use a step-debugger to see what's your code is doing. Commented Sep 28, 2011 at 8:44
  • Could you rephrase that a bit? If a row was deleted, how do you expect to retrieve it? Commented Sep 28, 2011 at 8:44
  • 1
    Isn't that you are always in the else? Commented Sep 28, 2011 at 8:46
  • If you say $del_array contains the whole result, then it means that the condition if ($db_array[$j]['ID'] == $row['id']) is not properly defined as it never sets to true. Commented Sep 28, 2011 at 8:46

1 Answer 1

2

According to the PHP manual:

1) break ends execution of the current for, foreach, while, do-while or switch structure
2) break accepts an optional numeric argument which tells it 
how many (the above mentioned) nested enclosing structures are to be broken out of

Your break is at the level 2, and hence break 2; should work as expected, so the problem is elsewhere. Is the break 2 executed at all?

In any case, I would recommend a more robust solution, e.g.

$ok = True;
while (($row = mysql_fetch_array($result)) && $ok) {
      ...
      if (...) $ok = False;  // anywhere deep
      ...
      if ($ok) {...}
}
Sign up to request clarification or add additional context in comments.

2 Comments

break ends execution of the current for, foreach, while, do-while or switch structure, so break 2 would work as expected
Thank you Jiri and matino. However, break 1 worked for me. It was a logic error from my side that I could not figure out at that moment.

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.