Esocoder
Esocoder

Reputation: 1061

How to produce the following sequence of numbers through a php for statement

I need to find out a way to output the following number sequence through a double php for statement:

0 - 1    <-- begin
0 - 2
0 - 3
0 - 4
1 - 1   
1 - 2
1 - 3
1 - 4
2 - 2
2 - 3
2 - 4
3 - 3
3 - 4    <-- end

How can I make the second loop, lose its first number, after each loop so the sequence looks like the output above?

I've been trying things like:

    for($z = 0; $z <= 3; $z++) {
        for($y = 0; $y <= 3; $y++) {

            echo $z . " - " . $y . "<br />";

        }
    }

But the second loop keeps starting with a number 1. But I can't even think of a way to do it at all.

Upvotes: 0

Views: 124

Answers (2)

user3035850
user3035850

Reputation:

Use a nested loop and let the nested one start at the iteration of the outer one:

for ($i = 0; $i < $max; $i++)
    for ($j = $i; $j < $max; $j++)
        echo "$i - $j";

Upvotes: 1

Hartmut Holzgraefe
Hartmut Holzgraefe

Reputation: 2765

for ($x = 0; $x <= 3; $x++) {
  for ($y = 1; $y <= 4; $y++) {
    if ($y >= $x) {
      echo "$x - $y\n";
    }
  }
}  

Upvotes: 2

Related Questions