tags:

views:

73

answers:

3

Hi everyone,

I have the following code, not written bymyself, but I am wondering if you could spot anything wrong with it?

$query =    "SELECT * from #__properties_type where published = 1 AND parent =        ".$Category_id." OR parent = 0";

$db->setQuery( $query );                

$types = $db->loadObjectList();

$nP = count($types);

$mitems[0]->id=0;

$mitems[0]->name='Type';

    foreach ( $types as $item ) {

        $mitems[] = $item;

    }

It seems to work fine but sometimes I will see a random Warning: Invalid argument supplied for foreach() in etc/etc/etc/

Any ideas?

+3  A: 

Your loadObjectList function seems to return a non-array sometimes, maybe when the SQL query fails.

Quick fix:

if (is_array($types))
foreach ( $types as $item ) {

        $mitems[] = $item;

    }

but you should look for the deeper cause why the function fails, and handle the error accordingly if there is one.

Pekka
Thank you, this worked!
skarama
A: 

It probably means your $types variable isn't being set. This will set a PHP warning off.

kylex
Is there a way to fix that? I found some reference online saying this warning can be stopped as such: " You can prevent this error by type-casting the foreach variable as an array type using "(array)" before the array variable name."
skarama
See my answer for a fix.
Pekka
A: 

Unless $mitems[0] is predefined before your code snippet, there's no way PHP can know about $mitems[0] contains an object, hence $mitems[0]->id will throw an warning.

To solve this:

$mitems[0] = new YourObject();
$mitems[0]->id=0;
$mitems[0]->name='Type';
rockacola