Reputation: 13
<?php
for( $t=0;$t<=9;$t++ ){
for( $o=0;$o<=9;$o++ ){
for( $g=0;$g<=9;$g++ ){
echo $t.$o.$g."<br />";
}
}
}
?>
This program gives an output of :
000 001 002 003 004 005 006 007 008 009 010 011 012 013 014 015 016 017 018 019 020 021 022 023 024 025 026 027 028 029 030 031 032 033 034 035 036 037 038 039 040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 TILL 999
I want to acheive such a thing using recursion ..say i want to do the same for four nested loops : I have written a program for this but in vain :
<?php
$done = array("t","o","g");
$i = 0;
function recurse($x){
//$done = array("t","o","g");
global $done;
global $i;
global $t;
global $o;
global $g;
$i++;
for( $$x=0;$$x<=9;$$x++ ){
if( $x!="g" ){
recurse($done[$i]);
}else{
echo $t.$o.$g."<br />";
$i=0;
} //if else
} // for end
} //function end
echo "{$done[0]} {$done[1]} {$done[2]}<br />";
recurse($done[0]);
print_r($done);
?>
OUTPUT : t o g 000 001 002 003 004 005 006 007 008 009 000 001 002 003 004 005 006 007 008 009 000 001 002 003 004 005 006 007 008 009 000 001 002 003 004 005 006 007 008 009
So instead of 010 011 012 after 009 its going back to 000 . Help appreciated!
Upvotes: 1
Views: 565
Reputation: 214949
I guess you're looking for something like this:
function enum($n) {
if($n == 0)
return array('');
$result = array();
foreach(enum($n - 1) as $e)
foreach(range(0, 9) as $k)
$result []= $e . $k;
return $result;
}
print_r(enum(3));
Upvotes: 0