Page 1 of 1

Warning: Invalid argument supplied for foreach()

Posted: Thu Mar 15, 2007 6:24 pm
by mikebr
The Ninja Space Goat | Please use

Code: Select all

, [code=text]<div class=\"text\" id=\"{CB}\" style=\"font-family: monospace;\"><ol><li style=\"\" class=\"li1\"> and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: :arrow: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]</li><li style=\"\" class=\"li2\">&nbsp;</li><li style=\"\" class=\"li1\">&nbsp;</li><li style=\"\" class=\"li2\">Hi,</li><li style=\"\" class=\"li1\">&nbsp;</li><li style=\"\" class=\"li2\">I have a foreach statement that runs through an array for $f but when the array has no values I get:</li><li style=\"\" class=\"li1\">Warning: Invalid argument supplied for foreach().......</li><li style=\"\" class=\"li2\">&nbsp;</li><li style=\"\" class=\"li1\">So as a test I set $f['test']=''; and I don't get the error, I though if I count the elements in the array and they where less than 1 I could avoid the error using the 'if ($f_count>0) {' but I find that it makes no difference if I set if '$f['test']='';' or not the count is still 1, anyone explain why this is and a way of maybe getting round the problem?</li><li style=\"\" class=\"li2\">&nbsp;</li><li style=\"\" class=\"li1\">[code]$f_count = count($f);</li><li style=\"\" class=\"li2\">&nbsp;</li><li style=\"\" class=\"li1\">if ($f_count>0) {</li><li style=\"\" class=\"li2\">foreach ($f as $key => $value) {</li><li style=\"\" class=\"li1\">// Code </li><li style=\"\" class=\"li2\">}</li><li style=\"\" class=\"li1\">}</li></ol></div>
 The only time I use $f before the foreach() is to get it's value and run it through a function to loop and stripslashes from any elements:

Code: Select all

$f = ($f) ? stripslashes_deep($_POST['f']) : '';
Thanks


The Ninja Space Goat | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]

Posted: Thu Mar 15, 2007 6:30 pm
by Luke
check if it is an array before trying to loop through it with foreach...

Code: Select all

$f_count = count($f);

if (is_array($f))
{
    foreach ($f as $key => $value)
    {
        // do stuff...
    }
}
else
{
    // do other stuff...
}

Posted: Thu Mar 15, 2007 6:43 pm
by mikebr
Cheers, that seemed to do the trick.