PHP: Using $count++ in an if condition

17,768

Solution 1

  • $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.

Solution 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.

Share:
17,768
David Angel
Author by

David Angel

Web Developer. Always learning more.

Updated on June 04, 2022

Comments

  • David Angel
    David Angel almost 2 years

    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;
        ...
    }
    
    • Álvaro González
      Álvaro González over 10 years
      I suppose you've tested it and found results you didn't understand. Can you share the details with us?
    • gen_Eric
      gen_Eric over 10 years
      This should work. $count++ will increment $count and return its original value.
  • War10ck
    War10ck over 10 years
    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.
  • Jack
    Jack over 10 years
    @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.
  • War10ck
    War10ck over 10 years
    @GeminiDomino Ahhh, yes. Sorry that was a really dumb question. I see it now. Thanks buddy. Appreciate the explanation. :)
  • Jack
    Jack over 10 years
    De nada. Pre/post-incrementation, I've learned, can be deceptively nuanced. :)