1

I have a class system and a function inside it that does a foreach from DB results. The variable is assigned inside the foreach, but outside of the foreach it is empty.

// Top of file
private $movieList = array();

if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                // add each to the array
                $this->movieList[] = array('nid' => $row->nid, 'title' => $row->title, 'movie_pos_id' => $row->movie_pos_id);
                print_r($this->movieList); // variable full of stuff
            }
            // No results found
            return false;
        }

print_r($this->movieList); // variable empty

Any idea why?

2
  • 2
    can you post the entire code; my bet is that you're printing it before the loop actually runs Commented Mar 6, 2012 at 16:25
  • It was not that $query->num_rows() > 0. Commented Mar 6, 2012 at 16:25

2 Answers 2

2

Looks to me like your line outside the if statement would never execute because you always return false if you got results. Check your brackets. You probably mean this:

if ($query->num_rows() > 0) {
    foreach ($query->result() as $row) {
        // add each to the array
        $this->movieList[] = 
            array('nid' => $row->nid, 'title' => $row->title, 
                'movie_pos_id' => $row->movie_pos_id);
        print_r($this->movieList); // variable full of stuff
    }
}
else {
    // No results found
    return false;
}

print_r($this->movieList);
Sign up to request clarification or add additional context in comments.

1 Comment

LOL I can't believe that... lol Thanks, I need to stop coding at night.
1

Your braces are mismatched. Try this

// Top of file
private $movieList = array();

if ($query->num_rows() > 0) {
            foreach ($query->result() as $row) {
                // add each to the array
                $this->movieList[] = array('nid' => $row->nid, 'title' => $row->title, 'movie_pos_id' => $row->movie_pos_id);
                print_r($this->movieList); // variable full of stuff
            }
}else{
            // No results found
            return false;
}


print_r($this->movieList); // variable empty

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.