What’s wrong with this Array? giving me Invalid argument supplied for foreach() in functions.php

I am developing WordPress Theme, i am using Redux Framework for getting user options. I want to create widgets dynamically according to which category user selected. These widgets will be shown in the category page on specific category front end user selected.

Redux Framework is returning array having checked and non-checked categories. Checked categories has value of 1 and non-checked has values of 0

Read More

The following is the output when i print_r($redcats)

Array
(
    [14] => 1
    [13] => 1
    [7] => 0
    [1] => 1
)

In header.php when i run code only to extract indexes which contain value of 1, code run perfect and gives me what i want using foreach() loop so that i can get category name and category slug later on as follows,

    $redcats = $mythemeslug['opt_extrac_widgets_selected'];
    foreach($redcats as $key=>$val)
    {
        if($val == 1)
        {
            echo "Category is ".returncatname1($key)." | and Slug is "
           .returncatslug1($key)."</br>";
        }
    }

    function returncatslug1($id)
    {
        $category = get_category( $id );
        return $category->slug;
    }

    function returncatname1($id)
    {
        $catname = get_cat_name($id);
        return $catname;
    } 

The following is the output since i ran entire codes in header.php first to test if everything is working well:

Category is History | and Slug is history
Category is My Gossipz | and Slug is my-gossipz
Category is Uncategorized | and Slug is uncategorized

but when i place the same foreach loop in functions.php gives me an error

Warning: Invalid argument supplied for foreach() in 
C:xampphtdocswpwp-contentthemes**themename**functions.php on line 111

where line 111 contains the following code.

$redcats = $mythemeslug['opt_extrac_widgets_selected'];
foreach($redcats as $key=>$val)
{
 //some codes comes in..
}

I wonder why i am getting Warning: Invalid argument supplied for foreach() in C:xampphtdocswpwp-contentthemes**themename**functions.php on line 111
while in header.php when i run the same code give correct results..

Note that, $mythemeslug['opt_extrac_widgets_selected'] is the Redux Framework returned results and i have other Redux Framework options already being manipulated in functions.php and they are working correctly

For reference: In Redux Framework options file, the code used to get categories is

array(
    'id'       => 'opt_extrac_widgets_selected',
    'type'     => 'checkbox',
    'title'    => 'Activate Category to have its own Widgets',
    'required' => array( 'opt_extrac_widgets_set', '=', '1' ),//depends on above option.
    'data'     => 'categories'
   ),

Related posts