-1

I would like to make a list of every possible combination of inserted numbers. I figured out this way:

     for($x=1;$x<=3;$x++){
         for($y=1;$y<=3;$y++){
             for($e=1;$e<=3;$e++){

             echo $x.$y.$e."</br>" ;

            }
          }   
        }

But the problem with these nested loops is that I have to put manually as many loops as I have digits in a number. Is there a way to make it automatically/programmatically?

Bunny Davis
  • 407
  • 4
  • 9

1 Answers1

0

You can use a recursive function to loop again when necessary.

For example, this function prints out the numbers 1-3 for a given number of digits (minimum allowed value is 1, any lower it will still output all single-digit numbers in that range):

function variations($digits, $prefix = '') {
    for ($i = 1; $i <= 3; $i++) {
        $variation = $prefix . $i;

        if ($digits > 1) {
            variations($digits - 1, $variation);
        } else {
            echo $variation . "<br />";
        }
    }
}

variations(1);
/*
1<br />2<br />3<br />
*/

variations(2);
/*
11<br />12<br />13<br />21<br />22<br />23<br />31<br />32<br />33<br />
*/

https://3v4l.org/Rj2u7 (outputs a linebreak instead of "<br />" for display purposes)

Here's a slight variation that returns the generated numbers in an array instead of echo'ing them directly, so you can use them for some other purpose if you'd like:

function variations($digits, $prefix = '') {
    $result = [];

    for ($i = 1; $i <= 3; $i++) {
        $variation = $prefix . $i;

        if ($digits > 1) {
            $result = array_merge($result, variations($digits - 1, $variation));
        } else {
            $result[] = $variation;
        }
    }

    return $result;
}

print_r(variations(1));
/*
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
*/

print_r(variations(2));
/*
Array
(
    [0] => 11
    [1] => 12
    [2] => 13
    [3] => 21
    [4] => 22
    [5] => 23
    [6] => 31
    [7] => 32
    [8] => 33
)
*/

https://3v4l.org/LBrjA

rickdenhaan
  • 10,857
  • 28
  • 37