34

Why am I getting this PHP Warning?

Invalid argument supplied for foreach()

Here is my code:

// look for text file for this keyword
if (empty($site["textdirectory"])) {
    $site["textdirectory"] = "text";
}
if (file_exists(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt')) {
    $keywordtext = 
     file_get_contents(ROOT_DIR.$site["textdirectory"].'/'.urlencode($q).'.txt');
}
else {
    $keywordtext = null;
}

$keywordsXML = getEbayKeywords($q);

foreach($keywordsXML->PopularSearchResult as $item) {
    $topicsString = $item->AlternativeSearches;
   $relatedString = $item->RelatedSearches;
   if (!empty($topicsString)) {
        $topics =  split(";",$topicsString);
    }
    if (!empty($relatedString)) {
        $related = split(";",$relatedString);
    }

}

$node = array();
$node['keywords'] = $q;

2

$xml = ebay_rss($node);

$ebayItems = array();
$totalItems = count($xml->channel->item);

$totalPages = $totalItems / $pageSize;


$i = 0;
foreach  ($xml->channel->item as $item) {
  $ebayRss = 
    $item->children('http://www.ebay.com/marketplace/search/v1/services');

    if ($i>=($pageSize*($page-1)) && $i<($pageSize*$page)) {
        $newItem = array();
        $newItem['title'] = $item->title;
        $newItem['link'] = buyLink($item->link, $q);
        $newItem['image'] = ebay_stripImage($item->description);
        $newItem['currentbid'] = ebay_convertPrice($item->description);
        $newItem['bidcount'] = $ebayRss->BidCount;
        $newItem['endtime'] = ebay_convertTime($ebayRss->ListingEndTime);
        $newItem['type'] = $ebayRss->ListingType;
        if (!empty($ebayRss->BuyItNowPrice)) {
            $newItem['bin'] = ebay_convertPrice($item->description);
        }
        array_push($ebayItems, $newItem);
    }
    $i++;
}


$pageNumbers = array();
for ($i=1; $i<=$totalPages; $i++) {
    array_push($pageNumbers, $i);
}

3

// get user guides
$guidesXML = getEbayGuides($q);
$guides = array();
foreach ($guidesXML->guide as $guideXML) {
    $guide = array();
    $guide['url'] = makeguideLink($guideXML->url, $q);
    $guide['title'] = $guideXML->title;
    $guide['desc'] = $guideXML->desc;
    array_push($guides,$guide);
}

What causes this warning?

Thamilhan
  • 13,040
  • 5
  • 37
  • 59
meme
  • 407
  • 1
  • 4
  • 3
  • 1
    Check out the `{}` button on the edit screen: It'll format the code for you like i've done now ;) – Nanne Jul 04 '11 at 13:18
  • 1
    Because you supplied an invalid argument to `foreach`. Did you check *what* you feed into it? `var_dump` can help you. – Jon Jul 04 '11 at 13:18
  • 1
    Which one of the `foreach` produces the error? Your error message should give you a line number... – Michael Berkowski Jul 04 '11 at 13:18
  • It has a PHP Warning: Invalid argument supplied for all three: foreach($keywordsXML->PopularSearchResult as $item) { foreach ($xml->channel->item as $item) { foreach ($guidesXML->guide as $guideXML) { – meme Jul 04 '11 at 14:35

4 Answers4

90

You should check that what you are passing to foreach is an array by using the is_array function

If you are not sure it's going to be an array you can always check using the following PHP example code:

if (is_array($variable)) {

  foreach ($variable as $item) {
   //do something
  }
}
dkinzer
  • 32,179
  • 12
  • 66
  • 85
  • 2
    Why, I'm asking what would be causing me to get. Why am I getting a PHP Warning: Invalid argument supplied for foreach() on three of my foreach in my script. – meme Jul 04 '11 at 14:44
  • In most cases this will work but not always see: http://stackoverflow.com/a/2630032/560287 – John Magnolia Sep 19 '13 at 12:34
  • Excellent. I was having an issue for a custom Wordpress plugin where I parse an RSS feed. This feed doesn't always have content by default, and expires until there is more content. So the array is not always populated. This solved the "offset" warnings I was getting in that case. – Heres2u Apr 20 '18 at 20:14
12

This means that you are doing a foreach on something that is not an array.

Check out all your foreach statements, and look if the thing before the as, to make sure it is actually an array. Use var_dump to dump it.

Then fix the one where it isn't an array.

How to reproduce this error:

<?php
$skipper = "abcd";
foreach ($skipper as $item){       //the warning happens on this line.
    print "ok";
}
?>

Make sure $skipper is an array.

Eric Leschinski
  • 146,994
  • 96
  • 417
  • 335
Nanne
  • 64,065
  • 16
  • 119
  • 163
7

Because, on whatever line the error is occurring at (you didn't tell us which that is), you're passing something to foreach that is not an array.

Look at what you're passing into foreach, determine what it is (with var_export), find out why it's not an array... and fix it.

Basic, basic debugging.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
3

Try this.

if(is_array($value) || is_object($value)){
    foreach($value as $item){
     //somecode
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
Mr Nobody
  • 397
  • 4
  • 4