0

I am trying a basic program to count from 3 in 3 until I reach 10. I tried:

<?php
  $a = 0;
  $b = 0;
  while ($a < 10) {
    $a += $b + 3;
    echo "$a\n\r";
  } 
?>

The output is 3, 6, 9, 12. And the expected output would be 3, 6, 9. because I added < 10. Why is it doing this? Sorry for my noob question, but it's confusing: http://codepad.org/Y8yhd0JP

2
  • 2
    Note that 9 < 10 soo .. 9+3= 12 ! Commented Apr 5, 2014 at 8:30
  • Aha got it, but it is also echoing 0, I think i need to add an if here.
    – Adrian
    Commented Apr 5, 2014 at 8:32

6 Answers 6

5

The value of $a is $a=9 in the 3rd iteration, so the loop will continue to go on to add upto 12.

To obtain the result as 3,6,9 check for while($a < 9){...}

<?php
  $a = 0;
  $b = 0;
  while ($a < 9) {
    $a += $b + 3;
    echo "$a\n\r";
  } 
?>
2
  • You are welcome :), If you wish to close off the question, mark the answer maybe ? Commented Apr 5, 2014 at 8:37
  • Sure, if I would have had more than 15 rep, would have also upvoted.
    – Adrian
    Commented Apr 5, 2014 at 8:38
2

This would be better to do with a do-while cycle, with $a initialised to its starting value before the cycle

<?php
  $b = 0;
  $a += $b + 3;
  do {
    echo "$a\n\r";
    $a += $b + 3;
  } while ($a < 10); 
?>
0
1

The while will check if the value in $a is more than 10.
After the check you add to the value and print it, then check again, if its over 10, it will not do another loop.
So when it prints 12, it will have checked if $a was over 10, which is was not, cause it was 9. Then do the addition and echo and check again and exit.

1

To start with, note the $b is always 0, so you can eliminate it like this:

  $a = 0;
  while ($a < 10) {
    $a += 3;
    echo "$a\n\r";
  } 

Note that you change the value of $a between the test and the echo. That is probably the reason for your surprise.

A better way to write it would be

for ($a = 3; $a < 10; $a += 3) {
    echo "$a\r\n";
}
1

An uglier solution:

$a = 0;
$b = 0;
while (($a += $b + 3) < 10)
  echo "$a\n\r";

I moved the addition in the while loop. Here you dont't have to put the echo in {} because there's only one statement.

0

in your code you are printing the element after it is increased, so after it prints 9 , it checks the condition ($a < 10) , the condition is true so it proceeds and print 12 , while the next iteration the condition ($a < 10) fails and it stops. this is the reason , you can avoid it by changing your code as follows,

 <?php
 $a = 0;
 $b = 0;
 while ($a < 9) {
   $a += $b + 3;
   echo "$a\n\r";
 } 
 ?>

Hope it helps.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.