looping problem

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
gortwell
Forum Newbie
Posts: 2
Joined: Sun Aug 14, 2011 6:48 pm

looping problem

Post by gortwell »

Hi,

Strange this but

Code: Select all

<?php
    for ($i=1; $i<=4; $i++) {
        for ($j=1; $j<=4; $j++) {
            for ($k=1; $k<=4; $k++) {
                if (($i == $j) || ($i == $k) || ($j == $k)) { break; }  # don't want duplicate numbers
                echo $i."   ".$j."   ".$k."   "."<br>";
            }
        }
    }
?>
I would have expected this output

Code: Select all

1 2 3
1 2 4
1 3 2
1 3 4
1 4 2
1 4 3
2 1 3
2 1 4
2 3 1
2 3 4
2 4 1
2 4 3
3 1 2
3 1 4
3 2 1
3 2 4
3 4 1
3 4 2
4 1 2
4 1 3
4 2 1
4 2 3
4 3 1
4 3 2
but get this shorter output

Code: Select all

2 3 1
2 4 1
3 2 1
3 4 1
3 4 2
4 2 1
4 3 1
4 3 2 
How come I'm missing 2/3 my expected results?

Many thanks

GW
User avatar
twinedev
Forum Regular
Posts: 984
Joined: Tue Sep 28, 2010 11:41 am
Location: Columbus, Ohio

Re: looping problem

Post by twinedev »

You are using break which STOPS the most resent foreach. You want continue which says skip the rest of the block of the most recent foreach, so then it will continue on with the next number (instead of completely stopping it).

-Greg
User avatar
Christopher
Site Administrator
Posts: 13596
Joined: Wed Aug 25, 2004 7:54 pm
Location: New York, NY, US

Re: looping problem

Post by Christopher »

It might want to break in the $j loop and continue in the $k loop.
(#10850)
gortwell
Forum Newbie
Posts: 2
Joined: Sun Aug 14, 2011 6:48 pm

Re: looping problem

Post by gortwell »

Thanks twinedev and Christopher. :)

Seems I misunderstood what 'break;' does.

GW
Post Reply