0

Possible Duplicate:
Php for loop with 2 variables?

Is there a way to make it shorter:

for ($x = 1; $x <= 5; $x++) {
for ($y = 1; $y <= 5; $y++) {
    echo $x, ' ', $y, '<br>';
}
}

2 for loops seems awkard

Community
  • 1
  • 1
Szymon Toda
  • 4,454
  • 11
  • 43
  • 62
  • What is it that you want to achieve? There are some things which mst have nested looping, awkward or not! – SexyBeast Sep 09 '12 at 12:03

4 Answers4

2

Not really, there is nothing wrong with nested loops.

Rich Bradshaw
  • 71,795
  • 44
  • 182
  • 241
1

It's hard to tell without knowing what is happening inside the loop. Why do you have two loops in the first place?

If you only need to loop something 25 times, you can do that in one loop:

for ($x = 1; $x <= 25; $x++) {
    //Looped code
{

But if you need to have the different variables ($x and $y) then it's more difficult to tell.

Ikke
  • 99,403
  • 23
  • 97
  • 120
0

It's alright. When you have 4 or 5 for-loops then you should think about optimization.

0

You can also use comma separated multiple variables in one for-loop.

for ($i = 1, $j = 0; $i <= 10 && $j < 5; $i++, $j++)
Louis Huppenbauer
  • 3,719
  • 1
  • 18
  • 24