tags:

views:

41

answers:

2

Error I'm receiving Invalid argument supplied for foreach()

The offending portions is this:

foreach($subs[$id] as $id2 => $data2)

Strange cause I'm using the same construct elsewhere and it works fine.. I'm using it to generate sub-categories and it works but I want to get rid of the error

This is more context

foreach($parents as $id => $data)
        {
            if($x == 0)
            {
                $html .= "<tr width='25%' class='row2'>";
            }

            $shtml = "";

            $i = 0;

            ***foreach($subs[$id] as $id2 => $data2)***
            {
                $i++;
                if($i == 15)
                {
                    $shtml .= $this->ipsclass->compiled_templates[ 'skin_businesses' ]->portal_categories_sub_row( $id2, $data2['cat_name'], 1 ) . "";
                    break;
                }
                else
                    $shtml .= $this->ipsclass->compiled_templates[ 'skin_businesses' ]->portal_categories_sub_row( $id2, $data2['cat_name'], 0 ) . "";
            }
+2  A: 

It may be that $subs[$id] is not consistently an array. That is, $subs[0] may be an array, but $subs[1] is a scalar.

Try casting it to be an array:

foreach((array)$subs[$id] as $id2 => $data2)

If $subs[1] is a scalar, then casting it forms an ephemeral array of one element for purposes of iterating over it.

Bill Karwin
Hey Bill that killed th error thanks a ton..
Just that casting to array worked around your error doesn't mean, it is really fixed. Instead of improvising a workaround you should better look for the cause of the problem. Fixes like this lead to really messy code that will be hard to debug and maintain.
Techpriester
Thanks @tech I commented it and will come back to it when time allows..
A: 

The variable that you pass to the loop is probably not an array. Try to debug your code to find out where it being assigned an value just before being fed into the loop.

If you assinged a single value to that variable somewhere, assign it like this:

$subs[1] = array('somevalue');

PHP is a dynamically typed language but knowing what type a variable has at any given moment is still very important.

Techpriester