棘手的循环代码

I have this simple code but I don't understand why the output is '234567' instead of '246'.

$a = 1;
while ($a < 10)
{
  echo $a+1;
  if ($a == 6)
  {
   break;
 }
 $a += 1;
}



Output:

234567

Because in the 4th line you are printing the result of ($a + 1) but you are NOT adding 1 to the variable $a.

Trace 1:

$a = 1

echo 1+1; // ($a + 1) 2. PRINTS two but $a is still 1
$a = $a + 1; // now $a is equal to 2 ( 1 + 1 )
// Current output 2

Trace 2:

$a = 2 // from trace 1

echo 2+1; // ($a + 1) 3. PRINTS 3 but $a is still 2
$a = $a + 1; // now $a is equal to 3 ( 2 + 1 )
// Current output 23

Trace 3:

$a = 3 // from trace 2

echo 3+1; // ($a + 1) 4. PRINTS 4 but $a is still 3
$a = $a + 1; // now $a is equal to 4 ( 3 + 1 )
// Current output 234

And so on.

To do what you wanted:

$a = 1;
while ($a < 10)
{
    echo ++$a;

    if ($a == 6) break;

    $a += 1;
}