Welcome Guest, Not a member yet? Register   Sign In
Problem with foreach in Model
#1

[eluser]Shpigford[/eluser]
I've got the following function in a model:
Code:
function getCategories()
    {
        
        $this->db->select('id, name, parent_id');
        $this->db->where('type', 'product');
        $this->db->where('active', 'Y');
        $this->db->where('parent_id', '0');
        
        $query = $this->db->get('categories');
        
        foreach ($query->result() as $category)
        {
            $output .= '<option value="'.$category->id.'">'.$category->name.'</option>';
        }
        
        return $output;
    }
But when I try to use the function I get: "Message: Undefined variable: output"
#2

[eluser]cinewbie81[/eluser]
Maybe :
Code:
$output = '';
        foreach ($query->result() as $category)
        {
            $output .= '<option value="'.$category->id.'">'.$category->name.'</option>';
        }
        
        return $output
#3

[eluser]Shpigford[/eluser]
Well...that worked.

But I guess the question here is why did I have to do that?
#4

[eluser]cinewbie81[/eluser]
What will happened if count for $query->result() is 0 ??
$output will never been declared then ..
hence the error : Undefined variable: output
#5

[eluser]charlie spider[/eluser]
writing
Code:
$output = $some_stuff;
does two things at once.
it declares the variable $output AND it assigns a value to it.

using .= (dot equals) is the same as writing
Code:
$output = $output + $some_stuff;

which doesn't work because the declaration of $ouput hasn't been finalized yet, so basically you can't add some_stuff to something that doesn't exist yet.




Theme © iAndrew 2016 - Forum software by © MyBB