2

Why is while loop showing 2 different outputs?

      $a=1;
    while ($a++ <4) {
       echo $a. "<br>";

    }  // output is 2 3 4 but (4 is not less than 4 )



      $a=1;
    while (++$a <4) {
       echo $a. "<br>";

    }       // output is  2 3

Please, can someone explain me the difference in detail? in $a++ it is showing output 2 3 4 but 4 is not less than 4 in while condition then why it is showing 4 which is not satisfying the condition?

2 Answers2

0
  • ++$a increases value before execute

  • $a++ increases value after execute

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
Rafeeq Mohamed
  • 182
  • 1
  • 4
  • 14
0

In simple anwer, when ++ use as suffix, php first execute while, then add 1 number to $a, Meaning in first while your start $i is 1.

And when ++ use as prefix, php first add 1 number to $a, then execute while, Meaning last while your start is 2.

This is same your code:

$a=1;
while ($a++ <4) {
   echo $a. "<br>";

}  // output is 2 3 4 but (4 is not less than 4 )
$a++;



$a=1;
$a++;
while (++$a <4) {
   echo $a. "<br>";

}       // output is  2 3
Hamid Abbasi
  • 346
  • 2
  • 14