views:

77

answers:

3

The code below shows nested while loops, but it's not the very efficient. Suppose I wanted to extend the code to include 100 nested while loops. Is there a better way to accomplish this task?

<?php 

$count = 1;

 $num = 1;
 $options=3;
 while ( $num <=$options ) 
    { 
echo "(".$num . ") "; 

    $num1 = 1; 
    $options1=3;
    while ( $num1 <=$options1 ) 
    { 
    echo "*".$num1 . "* "; 

        $num2 = 1; 
        $options2=3;
        while ( $num2 <=$options2 ) 
        { 
        echo "@".$num2 . "@ ";  

            $num3 = 1; 
            $options3=3;
            while ( $num3 <=$options3 ) 
            { 
            echo $num3 . " ";   
            $num3++; 
            $count++;
            }

        echo "<br />";
        $num2++; 
        }

    echo "<br />";
    $num1++; 
    }

echo "<br />";
$num++; 
} 
  echo $count;
 ?>
+3  A: 

You should probably adapt your algorithm to use recursion instead of a nested while loop.

webdestroya
A: 

You could use recursive functions.

Eric
A: 

It's perfectly efficient enough if the loops need to be nested.

As others have said, recursion would allow you to "nest" different levels within each other more elegantly, and the level of nesting could be controlled dynamically rather than being hard-coed into your program - but if you find your design requires you to nest 100 loops, then your design is almost certainly completely mad.

(However, in the specific example you give there is no need for any loops (or recursion) at all. As all the loops are of constant length, you can precalculate the result and just echo a single constant string. I presume this is a hyporthetical example rather than the actual code you wish to write?)

Jason Williams
Yep, completely hypothetical.
Ryan