views:

78

answers:

3

I'm getting an error and I've googled everything I can think of with barely any insights. Maybe you can help with a fresh set of eyes.

I have a function that returns an array of objects. The code that calls this function then loops through this array and does what it needs to do with each object. It seems to work visually when it spits out the HTML, but the server logs still give an error "Invalid argument supplied for foreach()". Yeah, it's great that it works technically, but I don't want this error to pop up anymore. Thoughts?

<?php

// The class whose method returns an array of library_Label objects
class library_Label
{
  public $id = null;
  public $name = null;

  public function getChildren()
  {
    // $children is declared earlier
    return $children;
  }
}


// main code
$columns = new library_Label(1);
foreach ($columns->getChildren() as $label) echo $label->Name;

?>
+1  A: 

You don't say what language you're using, but that looks like a PHP error. If so, check out PHP's error reporting levels. You should probably actually change the values in your php.ini, though, so that you don't dump out other errors into your server logs.

Of course, you'll want to find out why that error is being thrown regardless.

John Biesnecker
+1  A: 

The warning "Invalid argument supplied for foreach()" happens when you try to do a foreach on an variable that isn't an array.

You need to check that the return value from getChildren() actually is an array.

We can't tell this from your context since you've provided neither the constructor source nor the code that actually creates $children. If that were forthcoming, it might be easier to help you out.

One thing you could try is printing out the return value before executing the foreach, with "print_r($columns->getChildren())". This should be clear indication as to whether it's an array or not.

I'd also suggest checking to see if the array is empty, using empty() or count() - some sites on the net state that empty arrays will also cause this warning but I don't have a PHP environment at home to test that.

paxdiablo
+1  A: 

This is fairly common, my solution is always to change this:

foreach ($columns->getChildren() as $label) echo $label->Name;

to

$children = $columns->getChildren();
if (is_array($children)) foreach ($children as $label) echo $label->Name;

It should cover all situations.

You can expand it to a full if statement with braces as well and then include an else block to handle the situation when children is empty if you want to.

benlumley