1

I did this with a "for" loop. How can I write this with while. Thank you for your help. I just started learning PHP.

for ($a=0; $a <=10 ; $a++) { 
    for ($y=0; $y <= $a ; $y++) { 
        echo "*";
    }
    echo "<br>";
}
for ($a=10; $a >=1 ; $a--) { 
    for ($y=1; $y <= $a ; $y++) { 
        echo "*";
    }
    echo "<br>";
}
Apo
  • 47
  • 3
  • Not related to your question, but your inner loop can be replaced with `echo str_repeat('*', $a);` – Jerry Jul 27 '22 at 20:42

2 Answers2

1

The trick to rewriting a for statement to a while statement is extracting the incrementer initialization ($a = 0) and the incrementation ($a++) itself.

So

for ($a=0; $a <=10 ; $a++)

becomes

$a = 0;
while ($a <=10) {
    $a++;
}

Result

$a = 0;

while ($a <=10) {
    $y = 0;
    while ($y <= $a) { 
        echo "*";
        $y++;
    }
    echo "<br>";
    $a++;
}

$a = 10;

while ($a >=1) { 
    $y = 1;
    while ($y <= $a) { 
        echo "*";
        $y++;
    }
    echo "<br>";
    $a--;
}
Daniel
  • 10,641
  • 12
  • 47
  • 85
0
for ($i=10; $i<80; $i+=4) {
  // do something
}

is equivalent to:

$i=10
while ($i<80) {
  // do something
   $i+=4;
}
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
IT goldman
  • 14,885
  • 2
  • 14
  • 28