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;
$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); }
// 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?
The "invalid argument supplied for foreach() " error occurs when PHP's built-in foreach() tries to iterate over a data structure that is not recognized as an array or object. // a list/array, a boolean FALSE is returned.
The PHP foreach Loop The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
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 } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With