2

sorry about the funky title, I was having trouble coming up with one. First off, I managed to actually solve my problem (after tearing apart my code), but I have no idea WHY my solution worked and I am trying to treat this as a learning experience.

I have a class which collects info from the db. This class tracks an index value so that the calling function can grab the results one at a time. So my class code originally contained...

protected $index = NULL;
protected $array = array(stuff);

public function next_item()
{
    if($this->index == NULL)
    {//first time called
        $this->index = 0;
    }
    else
    {
        $this->index++;
    }

    if($this->index < sizeof($this->array))
    {
          return TRUE;
     }
      return FALSE;
 }

 public function get_result()
 {
      return $this->array[$this->index];
  }

And the calling function has something akin to

 while($myclass->next_item()){
        echo $myclass->get_result();
 }

It's all a lot more involved than this of course, but this is the problem code (and you get the idea). This code induced an infinite loop (or the appearance of one) in my project. I fixed my problem by initializing $index to -1, and removing the conditional check for null. So it's now ...

protected $index = -1;

public function next_item()
{
    $this->index++;

    if($this->index < sizeof($this->array))
    {
          return TRUE;
    }
    return FALSE;
}

My question is, WHY did that work? The index was never referenced in the array while it was NULL, I checked. It was always after the conditional check for NULL was called and the assignment to 0 occurred.

I really appreciate your time, in advance. Just trying to turn this into a learning experience, and it's better if I understand why it worked, not just that it did.

I'm sorry if this question is answered somewhere else, I couldn't figure out how to label my question (as you can see) much less have success finding a previous answer to it.

cheers, -David

dgeare
  • 2,525
  • 5
  • 16
  • 27
  • You can actually have `if (++$this->index < sizeof($this->array))` to save a line, it'll increment it for you. – DanRedux Jun 15 '12 at 03:43

1 Answers1

3

Your problem was caused by the fact that 0 == NULL in PHP. So when you set the index to 0 once you would keep setting it to 0 again over and over every time you call next_item, this->index == NULL would always be true.

Changing your test to this->index === NULL would have also solved your problem. See this question which covers the difference between == and === in PHP.

Community
  • 1
  • 1
Paul
  • 130,653
  • 24
  • 259
  • 248
  • Was beaten to the punch on this one. See [this thread on NULL vs FALSE vs 0](http://stackoverflow.com/questions/137487/null-vs-false-vs-0) – cpilko Jun 15 '12 at 03:34
  • Thanks very much, that was very helpful. I appreciate your time. – dgeare Jun 15 '12 at 19:51