1

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 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

1 Comment

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. "
0

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';

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.