Page 1 of 1

looping problem

Posted: Sun Aug 14, 2011 6:59 pm
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

Re: looping problem

Posted: Sun Aug 14, 2011 9:31 pm
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

Re: looping problem

Posted: Sun Aug 14, 2011 9:52 pm
by Christopher
It might want to break in the $j loop and continue in the $k loop.

Re: looping problem

Posted: Mon Aug 15, 2011 5:58 am
by gortwell
Thanks twinedev and Christopher. :)

Seems I misunderstood what 'break;' does.

GW