Question

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;
    ...
}
Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top