Click here to Skip to main content
14,639,264 members
Rate this:
Please Sign up or sign in to vote.
See more:
$arr= Array();
for ($a = 0; $a < 6; $a++){
    for ($b= 0; $b< 6; $b++){
        for ($c= 0; $c< 6; $c++){
            $arr[$a][$b][$c] = $a* $b* $c;
        }
    }
}


What I have tried:

how can i do this using only one loop ?
Posted
Updated 6-Aug-20 2:25am

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

There isn't really a more efficient - or maintainable - way to do that: you still have to "visit" each and every one of the 216 array elements and set it's value, so whatever you did to get a single loop to work would be less efficient - it would require "decoding" the single loop value to three array indexes, and that means either a lot of comparisons, or several divide / modulus operations. And they aren't "cheap"!

And even if you did, when the next spec change comes in and requires a array 12 x 15 x 3 instead of 6 x 6 x 6 you've got a really nasty set of changes to implement, test, and debug.

You are a lot better off leaving it as nested loops.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100