0

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

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I didn't notice that. I was so fixed in the echo function.
Here some interesting solution :D It's weird though $a = 0; while ($a < 6 && ($a+=2) && (print($a))); Just to mess around :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.