1

I have a question which I don't know the answer of. I've been thinking about it for a while.

The following code:

$i = 1;
while($i < 10) 
    if(($i++) % 2 == 0)
    echo $i;

It correctly outputs 3579, but why isnt 1 also included in the output?

I'm a beginner with PHP and am looking forward for someone to help me.

Thank you very much! :D

9
  • 5
    echo $1; TYPO maybe echo $i; would work better Commented Mar 11, 2019 at 12:11
  • 2
    It correctly outputs 3579.. How can this be? It throws a Fatal Error because of what @RiggsFolly mentioned Commented Mar 11, 2019 at 12:12
  • 2
    Also try incrementing $i AFTER you test it, not before Commented Mar 11, 2019 at 12:12
  • @B001ᛦ I am assuminmg thats a accident in the writing of the question :) Commented Mar 11, 2019 at 12:14
  • 1
    why isnt 1 also included in the output? because you are incrementing it i++ so it becomes 2. use $i=0; at the start Commented Mar 11, 2019 at 12:16

1 Answer 1

3

Two modifications:

$i = 0; // Make it 0 from 1
while($i < 10)
if(($i++) % 2 == 0)
echo "<br/>".$i; // Make $i instead of $1

Output:


1
3
5
7
9

Program hand run:

1) Set $i to 0.

2) If it is greater than 10, go ahead.

3) Increment it by 1

4) So, for $i => 0->1, 1->2

4) if new $i is even, print it. (So for first loop iteration, you are have $i -> 1 instead of 0 because of ++$i

Sign up to request clarification or add additional context in comments.

3 Comments

Hmm. Yes, now it does correctly output it, thank you! But, I still do not understand why. I'm not very good at PHP... trying to learn :). Could you explain in text, why it starts at 3 and not 1?
Because $i++ gets run before the % modulo therefore as you started %i at 1 it never saw a 1 the first time $i is tested it is already 2
Yep, got it. Thanks! :)

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.