4

I'm wondering if the $count++ way of incrementing a counter is okay to use in a conditional statement? Will the variable maintain it's new value?

$count = 0;
foreach ($things as $thing){
    if($count++ == 1) continue;
    ...
}
2
  • 6
    I suppose you've tested it and found results you didn't understand. Can you share the details with us? Commented Jan 8, 2014 at 15:30
  • 1
    This should work. $count++ will increment $count and return its original value. Commented Jan 8, 2014 at 15:30

2 Answers 2

9
  • $count++ is a post-increment. That means that it will increment after the evaluation.
  • ++$count is a pre-increment. That means that it will increment before the evaluation.

http://www.php.net/manual/en/language.operators.increment.php

To answer your question, that is perfectly valid, just keep in check that your value will be 2 after the if has been done.

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

4 Comments

Just out of curiosity, shouldn't $count be 1 after the evaluation. It's 0 to begin with. Incrementing would give you 1 would it not? I may be missing something though.
@War10ck: No, the if will be true if $count is 1, but since it's a post-increment, AFTER the if is determined to be true, THEN $count will be incremented, so it will be 2. The first iteration through the loop will evaluate the conditional to be false.
@GeminiDomino Ahhh, yes. Sorry that was a really dumb question. I see it now. Thanks buddy. Appreciate the explanation. :)
De nada. Pre/post-incrementation, I've learned, can be deceptively nuanced. :)
2

Yes, it will, but you want to pay attention to the difference between $count++(post-incrementation) and ++$count(pre-incrementation), or you might not get the results you expect.

For instance, the code snippet you wrote will "continue" on the second "$thing", but go through the loop on the first, because the value of $count won't be incremented until after its value is tested. If that's what you're going for, then right on, but it's one of those common "gotchas", so I thought I should mention it.

Comments

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.