Variable Number of Nested For Loops

An old problem that came to my head a couple of days ago. I solved it as an excersive in Fortran class about 25 years ago, my current solution is:


$lbound = 1;
$ubound = 4;
$loops = 3;

$numbers = array();
for($i=1; $i<=$loops; $i++) {
    $numbers[$i] = $lbound;
}

$nm = pow($ubound-$lbound+1,$loops);
printf("nm=%s\n", $nm);

$cnt = 0;
while(true) {
    printf("%s. %s\n",++$cnt, implode(',',$numbers));
    for($l=$loops; $l>=1; $l--) {
        $numbers[$l]++;
        if( $numbers[$l]>$ubound ) {
            $numbers[$l] = $lbound;
        }
        else {
            break;
        }
    }
    if( $cnt==$nm) {
        break;
    }
}