Invalid argument supplied for foreach
Invalid argument supplied for foreach
PHP Warning: Invalid argument supplied for foreach()
Why am I getting this PHP Warning?
Invalid argument supplied for foreach()
What causes this warning?
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
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:
This means that you are doing a foreach on something that is not an array.
Then fix the one where it isn’t an array.
How to reproduce this error:
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.
Invalid argument supplied for foreach()
It often happens to me to handle data that can be either an array or a null variable and to feed some foreach with these data.
When you feed a foreach with data that are not an array, you get a warning:
Warning: Invalid argument supplied for foreach() in [. ]
Assuming it’s not possible to refactor the get_values() function to always return an array (backward compatibility, not available source code, whatever other reason), I’m wondering which is the cleanest and most efficient way to avoid these warnings:
20 Answers 20
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The reason for my preference is it doesn’t allocate an empty array when you’ve got nothing to begin with anyway.
How about this one? lot cleaner and all in single line.
I usually use a construct similar to this:
Note that this particular version is not tested, its typed directly into SO from memory.
Edit: added Traversable check
Please do not depend on casting as a solution, even though others are suggesting this as a valid option to prevent an error, it might cause another one.
Be aware: If you expect a specific form of array to be returned, this might fail you. More checks are required for that.
Always test your input before using it in foreach. Suggestions:
JSON Invalid argument supplied for foreach()
I have some issue to retrieve data from JSON, it always said Invalid argument supplied for foreach(), this is the JSON in the url.php :
and this is my code :
5 Answers 5
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
You need to explicitly turn json_decode output to an array. Like this:
I had exactly same issue like yours and this resolved my issue.
Since your JSON is valid, next step is to check for PHP error in decoding.
First try this code to check error while decoding JSON:
Once you know the error you can search for more precise error from CONSTANT in case. Most like its ‘JSON_ERROR_UTF8’.
i was have this error too, and i have solved it using this:
so, your code should be like this:
Just remove the true in the json_decode() like this:
And take a quote from there:
assoc When TRUE, returned objects will be converted into associative arrays.
Please take a look at the assoc flag that you are setting to true when you call json_decode : http://php.net/manual/en/function.json-decode.php
it should work fine using the below code:
Not the answer you’re looking for? Browse other questions tagged php arrays json or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
I’ve a bug from this file :
Message: Invalid argument supplied for foreach()
thanks in advance for reading this 🙂
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The variable you supply to the foreach loop has to be an array. You can skip the foreach if the value of the variable supplied is not an array with the solution below.
If you are wondering what could be in the variable, output it!
That will instantly tell you what is going on. My guess, you have returned FALSE somewhere from your model, or you are using the DB object and not result() or result_array() (as suggested by Alex).
$result is not array.
Getting Message: Invalid argument supplied for foreach() when there is no records in the table
I have two tables with records. In the first table, I am displaying personal information and in the second table, I am adding the activities details.
Now I am trying to display the record using joins. So below code, I am using in the model
Controller
Note: I am getting multiple member id here because I have above some more logic. that’s the reason I am using for each.
Now If I found the records related the member id in the secondary table then I am getting the output but if not found a record in the second table then I am getting the error Message: Invalid argument supplied for foreach()
If I remove ‘member_activity.activity_status’=>1 from the where clause then my join query is working. I mean I am getting the member records.
View
So my expected output is, I have to display the records if found in the second table if not found then also display the member table records.
Disabling «invalid argument supplied» warning for a particular foreach
Can I disable warnings for particular foreach statements and more specifically the «invalid argument supplied» warning?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Alternative, type agnostic, using a typecast:
Would convert a NULL into an empty array, or a integer/string into an array with a single entry. This is sometimes advisable if you traverse flexible data structures (PHP is a dynamic language after all). The failure method is advisable for catching invalid data (should rather throw an error however).
No, not even using @ in front of the foreach (but that would be bad practice anyway).
Just do an easy is_array() check beforehand:
Error «Invalid argument supplied for foreach()» on my function [duplicate]
So, I have this function:
I’m getting a lot of these errors: FastCGI sent in stderr: «PHP message: PHP Warning: Invalid argument supplied for foreach(). The line of the problem is
What’s wrong with that?
Thanks in advance guys! 🙂
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
When you use json_decode you get an object. If you want an array you can use the second argument of json_decode which is a toggle for return an object or an array. true gives arrays.
You’ll need to adapt your code to use the new array.
Another thing that might help, (not sure, because i don’t know what’s in the object), is to cast the object to an array (but that is a bit of an hack ;)):
try the following before your foreach :
This is useful when what you get in the json is not always an array.
If it’s suppose to be an array, then use it only for debugging and do a var_dump($jsonData->data); in the else to see what you actually got
I want to insert record for each pincode into database but i am getting this error.Invalid argument supplied for foreach().
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I’m guessing you just miss typing explode to implode.
getting the following error “Warning: Invalid argument supplied for foreach() ”
Its because of either null or false or argument is not array
We can regenerate this error like this for example
So you need correct one line first
implode — Join array elements with a string
From
explode — Split a string by string
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
Invalid argument supplied for foreach()
Newbie here. I’ve been working on a one to many relationship in Laravel 5.4. I’m working on reading the relationship between User and State. I keep getting this error. I have data in the tables. Here is the view:
Here is the User model:
Here is the State model:
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Check array or object count before applying foreach loop. It is really a bad practice of using loop without checking the array count.
Undefined variable and Invalid argument supplied for foreach()
i’m trying to learn codeigniter and i have problem here. There was an error Undefined variable and Invalid argument supplied for foreach() on view. here is the code :
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
First check value return any value or not write this code in controller use
var_dump($firstnames) ; and var_dump($users) ;
I think no data return from model check any data in table Thanks
You can eliminate the error by using return []; instead of return null; instead of checking for that case in every foreach call, because it appears that your user table might be empty based on the code provided.
Invalid argument supplied for foreach; PDO
I have seen this and this, but neither of these help my situation, this is why I am knowledgeably opening a question that has been asked before.
The database is initialized and connected to in an include provided by my globhead file:
logPDO is provided by my functions class:
I’m not sure what’s going on, and I am very new to PDO, so I’m not sure how to troubleshoot this.
I have tried wrapping this in a try,catch block but nothing was reported (nor logged to file using my log function), so I’m at a loss. Does anyone with more experience with PDO see anything that’s wrong with my code?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I’m not sure what’s going on, and I am very new to PDO, so I’m not sure how to troubleshoot this.
What’s going on is, that you’ve got an empty database result. If you foreach over an empty result, there are no (zero) iterations. Hence you see no output and hence you see no error. It’s a perfectly fine programming of doing nothing.
Invalid argument supplied for foreach() warning
I want to insert json array data in mysql table. I have written this code.
Above code is working fine when I am using xampp. But when I have uploaded this code to server then same code is giving warning » Invalid argument supplied for foreach()» and not inserting in table. But using in xampp, code is working fine and inserting data successfully. Somebody help me..
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Not a complete answer but an observation that your code is vulnerable to SQL injection. Try:
I can’t tell for certain but your code may be confusing the OO (object oriented) and procedural form of mysqli. Stick to one or the other (OO form ideally)
For example in your original code, say someone sent you a malicious JSON object similar to the following:
Invalid argument supplied for foreach()
The code down below delete files inside the folder » Images » every 60 seconds, it works, but when the folder is empty it says: Warning: Invalid argument supplied for foreach() How can that be fixed like if there is no files, say » folder empty instead of that warning..
1 Answer 1
Since glob() may not reliably return an empty array for an empty match (See «note» in Return section of the docs), you just need an if statement protecting your loop, like so:
Not the answer you’re looking for? Browse other questions tagged foreach php or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
I am working to show editable fields based on query results. I know the query is functioning properly, and it is returning an array. The array is populating the form fields properly, however, I am getting the «Invalid argument supplied for foreach()» warning. I am new at this, and at a loss as to what is happening. I appreciate any suggestions.
‘; > foreach($row as &$item)
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
And then for each variable you should probably change
foreach($row as &$item) should be
there is no need to use the foreach here you can just do this like like
Invalid argument supplied for foreach() PHP OOP
I am new to PHP and I am trying to set up a CMS (content management system) using object oriented programming.
While re-factoring the code to make it simpler, I ran into an issue.
When I instantiate a class and call a function using the «auto instantiation», my array no longer works and comes back empty.
If I use the long form, it comes back with an array, but as I develop a real site this will become extremely time consuming to code this way.
Kind of lost, any help would be greatly appreciated thank you.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Having said that, if you’re trying to apply OOP concepts to your project you should start by separating concerns in your classes. This Users class is clearly doing too many things. It’s representing a User entity (or a collection of them), it’s acting as a Repository and also as a Factory.
You should try to split those things appart, which will make it much easier to reason about your code. Some ideas:
Invalid argument supplied for foreach; PDO
I have seen this and this, but neither of these help my situation, this is why I am knowledgeably opening a question that has been asked before.
The database is initialized and connected to in an include provided by my globhead file:
logPDO is provided by my functions class:
I’m not sure what’s going on, and I am very new to PDO, so I’m not sure how to troubleshoot this.
I have tried wrapping this in a try,catch block but nothing was reported (nor logged to file using my log function), so I’m at a loss. Does anyone with more experience with PDO see anything that’s wrong with my code?
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I’m not sure what’s going on, and I am very new to PDO, so I’m not sure how to troubleshoot this.
What’s going on is, that you’ve got an empty database result. If you foreach over an empty result, there are no (zero) iterations. Hence you see no output and hence you see no error. It’s a perfectly fine programming of doing nothing.
PHP Warning: Invalid argument supplied for foreach() on my script
Hi I am getting this errors in my php scipt :
error number 1. PHP Warning: Invalid argument supplied for foreach() in /home/tsbt/public_html/index.php on line 231
error numner 2. PHP Notice: Undefined offset:
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
That’s because you didnt supply an array or anything else you could iterate throuhg.
put before that foreach this line
error number 1
Use is_array check before foreach : http://php.net/manual/ru/function.is-array.php to avoid such error.
error number 2
Not the answer you’re looking for? Browse other questions tagged php foreach or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
I’ve a bug from this file :
Message: Invalid argument supplied for foreach()
thanks in advance for reading this 🙂
11 Answers 11
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The variable you supply to the foreach loop has to be an array. You can skip the foreach if the value of the variable supplied is not an array with the solution below.
If you are wondering what could be in the variable, output it!
That will instantly tell you what is going on. My guess, you have returned FALSE somewhere from your model, or you are using the DB object and not result() or result_array() (as suggested by Alex).
$result is not array.
Why always «Invalid argument supplied for foreach» [duplicate]
i want make a chart on codeigniter but i always fail. pls help me wrong text : A PHP Error was encountered
Severity: Warning Message: Invalid argument supplied for foreach() Filename: chart/index.php Blockquote Line Number : 16
please give me solution.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
or change your function get_chart to always return array:
Note: we can just return result() as the foreach in your example is unnecessary/redundant. Important that we return false as well.
PHP Database Invalid argument supplied for foreach()
Hi I’m very new to PHP because I just started learning this 2 days ago! I’m trying to display my second table properly in my index.html file but I get this error: Invalid argument supplied for foreach() Take a look
Any help would be much appreciated
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
to prevent double loading of your database file.
You might want to consider not disconnecting and connecting again
You have 6 th elements in the header and 7 td elements in your rows. Try to add a th in the header row.
This implies that the SQL query is failing (PDO returns false if the query fails). The manpage says
If you do not fetch all of the data in a result set before issuing your next call to PDO::query(), your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query().
after the for each loop, this should output the PDO error details.
Invalid argument supplied for foreach in ошибка
Разрабатывая свой код на PHP, программист может столкнуться с сообщением об ошибке « Invalid argument supplied for foreach in …». После данного сообщения обычно следует указание на её конкретику, к примеру, «/modules/tasks/todo_tasks_sub.php on line 121». Ошибка обычно обусловлена спецификой имеющегося отрезка кода, и требует проверки особенностей использования в нём переменных. Давайте разберём факторы появления ошибки, и как её можно исправить.
Причины появления Invalid argument supplied for foreach
Рассматриваемая ошибка обычно возникает в ситуации, когда переменная, которую foreach пытается выполнить (повторить) не является массивом. К примеру, вы передаёте в цикл не массив, а скаляр, или вы задействуйте двойной массив, и забыли определить, как выбирается индекс.
Давайте допустим, что мы имеем функцию с именем get_user_posts. Эта функция должна возвращать массив комментариев пользователя. Однако если комментариев нет, функция возвращает логическое значение FALSE.
Warning: Invalid argument supplied for foreach() on line 7
Как же решить указанную проблему? Давайте разбираться.
Как исправить ошибку «Invalid argument supplied for foreach in»
Решение зависит от того, для чего предназначен ваш код. То есть, если функция get_user_posts всегда должна возвращать массив, то, очевидно, вам необходимо выяснить, почему она возвращает логическое значение FALSE или значение NULL. Причиной этому может быть несколько вещей:
Просматривая чей-либо код, мы можем столкнуться с API и функциями, которые возвращают значение FALSE, когда результаты отсутствуют. Если это так, то вы можете добавить следующую проверку в ваш код:
Ошибка в WordPress
Также рассматриваемая ошибка может появляться при работе сайтов на WordPress. Проблема вызвана тем, что WP_Block_Parser выполняет несколько строковых манипуляций с substr () и strlen (), предполагая, что они работают с одиночными байтами, а не с многобайтовыми последовательностями.
Решить ошибку Invalid argument supplied for foreach в WordPress помогает изменение значения настройки mbstring.func_overload на 0 (обычно стоит 2). Сохраните произведённые изменения, и попытайтесь перейти на проблемную ранее страницу.
why this is Invalid argument supplied for foreach()?
I don’t understand why, the error says :
popuptweets.php code
and the error on foreach that’s means on this code
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Arguments for foreach must be an array, you need to var_dump($comments) to see whether it’s an array or not. In your case, returning result may be null so it returns warning for foreach. To ensure the foreach working, you may use this:
I compared your code with mine and found a difference in this line: Do not worry, the error is there.
Not the answer you’re looking for? Browse other questions tagged php html foreach or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
«Invalid argument supplied for foreach()» in WordPress
I’m creating a WP site. In the homepage, I’m getting an error:
Warning: Invalid argument supplied for foreach() in /home2/siilverp/public_html/wp-content/themes/mts_steadyincome/page-home.php on line 108
This is the code of page-home.php:
Now, I found that I have to type var_dump. Then, this appears:
array(84) < ["mts_logo"]=>string(0) «» [«mts_favicon»]=> string(0) «» [«mts_touch_icon»]=> string(0) «» [«mts_metro_icon»]=> string(0) «» [«mts_twitter_username»]=> string(0) «» [«mts_feedburner»]=> string(0) «» [«mts_header_code»]=> string(0) «» [«mts_analytics_code»]=> string(0) «» [«mts_ajax_search»]=> string(1) «0» [«mts_responsive»]=> string(1) «1» [«mts_rtl»]=> string(1) «0» [«mts_shop_products»]=> string(1) «9» [«mts_prefetching»]=> string(1) «0» [«mts_lazy_load»]=> string(1) «0» [«mts_lazy_load_thumbs»]=> string(1) «0» [«mts_lazy_load_content»]=> string(1) «0» [«mts_async_js»]=> string(1) «1» [«mts_remove_ver_params»]=> string(1) «1» [«mts_optimize_wc»]=> string(1) «1» [«mts_color_scheme»]=> string(7) «#3fc5a4» [«mts_layout»]=> string(8) «cslayout» [«mts_background»]=> array(10) < ["color"]=>string(7) «#ffffff» [«use»]=> string(7) «pattern» [«image_pattern»]=> string(4) «nobg» [«image_upload»]=> string(0) «» [«repeat»]=> string(6) «repeat» [«attachment»]=> string(6) «scroll» [«position»]=> string(8) «left top» [«size»]=> string(5) «cover» [«gradient»]=> array(3) < ["from"]=>string(7) «#ffffff» [«to»]=> string(7) «#000000» [«direction»]=> string(10) «horizontal» > [«parallax»]=> string(1) «0» > [«mts_custom_css»]=> string(0) «» [«mts_lightbox»]=> string(1) «0» [«mts_sticky_nav»]=> string(1) «0» [«mts_show_primary_nav»]=> string(1) «1» [«mts_show_footer_nav»]=> string(1) «1» [«mts_header_section2»]=> string(1) «1» [«mts_header_bottom_text»]=> string(17) «Download my Ebook» [«mts_header_bottom_button_text»]=> string(20) «Start Earning Today!» [«mts_header_bottom_button_link»]=> string(1) «#» [«mts_banner_show»]=> string(1) «1» [«mts_banner_image»]=> string(81) «https://seiscifrasonline.com/wp-content/themes/mts_steadyincome/images/header.jpg» [«mts_banner_title»]=> string(34) «Start Earning Steady Income Today!» [«mts_banner_texts»]=> string(156) «Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi at nisl lorem, vel porttitor justo. Nunc non mauris elit. Nam enim massa commodo ut placerat.» [«mts_button_text»]=> string(16) «Get Started Here» [«mts_banner_button_bg»]=> string(7) «#FF9742» [«mts_arrow_image»]=> string(80) «https://seiscifrasonline.com/wp-content/themes/mts_steadyincome/images/arrow.png» [«mts_form_image»]=> string(80) «https://seiscifrasonline.com/wp-content/themes/mts_steadyincome/images/money.png» [«mts_ribbon_show»]=> string(1) «1» [«mts_banner2_show»]=> string(1) «1» [«mts_social_title»]=> string(66) «Join Over 100,000 People in Our Online Community!» [«mts_banner_social»]=> array(5) < ["facebook"]=>array(5) < ["group_title"]=>string(8) «Facebook» [«group_sort»]=> string(1) «1» [«mts_banner_icon_title»]=> string(8) «Facebook» [«mts_banner_icon»]=> string(8) «facebook» [«mts_banner_icon_link»]=> string(1) «#» > [«twitter»]=> array(5) < ["group_title"]=>string(7) «Twitter» [«group_sort»]=> string(1) «2» [«mts_banner_icon_title»]=> string(7) «Twitter» [«mts_banner_icon»]=> string(7) «twitter» [«mts_banner_icon_link»]=> string(1) «#» > [«gplus»]=> array(5) < ["group_title"]=>string(11) «Google Plus» [«group_sort»]=> string(1) «3» [«mts_banner_icon_title»]=> string(11) «Google Plus» [«mts_banner_icon»]=> string(11) «google-plus» [«mts_banner_icon_link»]=> string(1) «#» > [«youtube»]=> array(5) < ["group_title"]=>string(7) «YouTube» [«group_sort»]=> string(1) «4» [«mts_banner_icon_title»]=> string(7) «YouTube» [«mts_banner_icon»]=> string(12) «youtube-play» [«mts_banner_icon_link»]=> string(1) «#» > [«rss»]=> array(5) < ["group_title"]=>string(3) «RSS» [«group_sort»]=> string(1) «5» [«mts_banner_icon_title»]=> string(3) «RSS» [«mts_banner_icon»]=> string(3) «rss» [«mts_banner_icon_link»]=> string(1) «#» > > [«mts_books_title»]=> string(51) «Recommended readings by John Smith» [«mts_books_image»]=> string(0) «» [«mts_more_book_link»]=> string(1) «#» [«mts_more_book_text»]=> string(10) «More Books» [«mts_featured_posts»]=> string(1) «1» [«mts_featured_post_cat»]=> string(1) «1» [«mts_featured_post_dedup»]=> string(1) «0» [«mts_first_footer»]=> string(1) «0» [«mts_first_footer_num»]=> string(1) «4» [«mts_footer_slider»]=> string(0) «» [«mts_copyrights»]=> string(73) «Theme by MyThemeShop» [«mts_home_post_layout»]=> string(8) «layout-1» [«mts_full_posts»]=> string(1) «0» [«mts_pagenavigation_type»]=> string(1) «1» [«mts_home_headline_meta_info»]=> array(2) < ["enabled"]=>array(3) < ["author"]=>string(11) «Author Name» [«date»]=> string(4) «Date» [«comment»]=> string(13) «Comment Count» > [«disabled»]=> array(0) < >> [«mts_single_post_layout»]=> string(0) «» [«mts_single_headline_meta_info»]=> array(2) < ["enabled"]=>array(4) < ["author"]=>string(11) «Author Name» [«date»]=> string(4) «Date» [«category»]=> string(10) «Categories» [«comment»]=> string(13) «Comment Count» > [«disabled»]=> array(0) < >> [«mts_breadcrumb»]=> string(1) «1» [«mts_author_comment»]=> string(1) «1» [«mts_comment_date»]=> string(1) «1» [«mts_home_social_buttons»]=> string(1) «1» [«mts_social_button_position»]=> string(3) «top» [«mts_social_buttons»]=> array(2) < ["enabled"]=>array(5) < ["facebookshare"]=>string(14) «Facebook Share» [«facebook»]=> string(13) «Facebook Like» [«twitter»]=> string(7) «Twitter» [«gplus»]=> string(11) «Google Plus» [«pinterest»]=> string(9) «Pinterest» > [«disabled»]=> array(2) < ["linkedin"]=>string(8) «LinkedIn» [«stumble»]=> string(11) «StumbleUpon» > > [«mts_posttop_adcode»]=> string(0) «» [«mts_posttop_adcode_time»]=> string(1) «0» [«mts_postend_adcode»]=> string(0) «» [«mts_postend_adcode_time»]=> string(1) «0» [«mts_custom_sidebars»]=> string(0) «» [«mts_sidebar_for_home»]=> string(0) «» [«mts_sidebar_for_post»]=> string(0) «» [«mts_sidebar_for_page»]=> string(0) «» [«mts_sidebar_for_archive»]=> string(0) «» [«mts_sidebar_for_category»]=> string(0) «» [«mts_sidebar_for_tag»]=> string(0) «» [«mts_sidebar_for_date»]=> string(0) «» [«mts_sidebar_for_author»]=> string(0) «» [«mts_sidebar_for_search»]=> string(0) «» [«mts_sidebar_for_notfound»]=> string(0) «» [«mts_sidebar_for_shop»]=> string(12) «shop-sidebar» [«mts_sidebar_for_product»]=> string(15) «product-sidebar» [«last_tab»]=> int(0) > Warning: Invalid argument supplied for foreach() in /home2/siilverp/public_html/wp-content/themes/mts_steadyincome/page-home.php on line 108
And from there, I don’t know what to do. I don’t know anything about programming.
PHP Database Invalid argument supplied for foreach()
Hi I’m very new to PHP because I just started learning this 2 days ago! I’m trying to display my second table properly in my index.html file but I get this error: Invalid argument supplied for foreach() Take a look
Any help would be much appreciated
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
to prevent double loading of your database file.
You might want to consider not disconnecting and connecting again
You have 6 th elements in the header and 7 td elements in your rows. Try to add a th in the header row.
This implies that the SQL query is failing (PDO returns false if the query fails). The manpage says
If you do not fetch all of the data in a result set before issuing your next call to PDO::query(), your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query().
after the for each loop, this should output the PDO error details.
Invalid argument supplied for foreach()
I am trying to install a theme locally but when I go to do it I get the following error:
If my problem lies in the slider code then that is below, but I don’t think there should be as I installed it fresh out of the box.
Your help would be much appreciated. Cheers, Rags
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
this is issued when a non-array object or value is passed in to foreach loop.
You might want to var_dump($slides); and see what it holds. It most likely holds a boolean false or null value.
Before using foreach loop I would check if $slides is an array
I have had problema with «foreach».
If I register something in PhpMyAdmin this code shows the register. But if there’s not register in DB the page shows
Warning: Invalid argument supplied for foreach() in C:\wamp64\www\banheiromovel\02-listagem\listagem_perfil.php on line 41
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
I think your two best options are either
Wrap the foreach in a conditional to make sure it’s not empty before you try to iterate it
Modify selecionar() so that it always returns an array, but just returns an empty array if the query returns no results.
I prefer the second one, personally. You can do this by initializing whatever variable you’re fetching your query results into in the function to an empty array, then returning that variable after you (possibly) fill it with data.
Also, you should be executing those queries using prepared statements. Inserting input into the SQL string like that is not safe.
Warning: Invalid argument supplied for foreach()
4 Answers 4
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Add this row in your while loop, and use the foreacn on this:
$strings will be FALSE when the foreach starts. This is because of the while above it. This loop will loop through all records, till mysql_fetch_array($str) returns FALSE and thus terminates the loop.
You should probably put the foreach code inside the while loop or use the while loop to collect the items you need and loop through those in the foreach loop.
Not the answer you’re looking for? Browse other questions tagged php mysql or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Error «Invalid argument supplied for foreach()» on my function [duplicate]
So, I have this function:
I’m getting a lot of these errors: FastCGI sent in stderr: «PHP message: PHP Warning: Invalid argument supplied for foreach(). The line of the problem is
What’s wrong with that?
Thanks in advance guys! 🙂
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
When you use json_decode you get an object. If you want an array you can use the second argument of json_decode which is a toggle for return an object or an array. true gives arrays.
You’ll need to adapt your code to use the new array.
Another thing that might help, (not sure, because i don’t know what’s in the object), is to cast the object to an array (but that is a bit of an hack ;)):
try the following before your foreach :
This is useful when what you get in the json is not always an array.
If it’s suppose to be an array, then use it only for debugging and do a var_dump($jsonData->data); in the else to see what you actually got
Invalid argument supplied for foreach() warning
I want to insert json array data in mysql table. I have written this code.
Above code is working fine when I am using xampp. But when I have uploaded this code to server then same code is giving warning » Invalid argument supplied for foreach()» and not inserting in table. But using in xampp, code is working fine and inserting data successfully. Somebody help me..
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Not a complete answer but an observation that your code is vulnerable to SQL injection. Try:
I can’t tell for certain but your code may be confusing the OO (object oriented) and procedural form of mysqli. Stick to one or the other (OO form ideally)
For example in your original code, say someone sent you a malicious JSON object similar to the following:
PHP Database Invalid argument supplied for foreach()
Hi I’m very new to PHP because I just started learning this 2 days ago! I’m trying to display my second table properly in my index.html file but I get this error: Invalid argument supplied for foreach() Take a look
Any help would be much appreciated
3 Answers 3
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
to prevent double loading of your database file.
You might want to consider not disconnecting and connecting again
You have 6 th elements in the header and 7 td elements in your rows. Try to add a th in the header row.
This implies that the SQL query is failing (PDO returns false if the query fails). The manpage says
If you do not fetch all of the data in a result set before issuing your next call to PDO::query(), your call may fail. Call PDOStatement::closeCursor() to release the database resources associated with the PDOStatement object before issuing your next call to PDO::query().
after the for each loop, this should output the PDO error details.
PHP Warning: Invalid argument supplied for foreach() on my script
Hi I am getting this errors in my php scipt :
error number 1. PHP Warning: Invalid argument supplied for foreach() in /home/tsbt/public_html/index.php on line 231
error numner 2. PHP Notice: Undefined offset:
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
That’s because you didnt supply an array or anything else you could iterate throuhg.
put before that foreach this line
error number 1
Use is_array check before foreach : http://php.net/manual/ru/function.is-array.php to avoid such error.
error number 2
Not the answer you’re looking for? Browse other questions tagged php foreach or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
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
The following is the output when i print_r($redcats)
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,
The following is the output since i ran entire codes in header.php first to test if everything is working well:
but when i place the same foreach loop in functions.php gives me an error
where line 111 contains the following code.
I wonder why i am getting Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\wp\wp-content\themes\**themename**\functions.php on line 111 while in header.php when i run the same code give correct results..
For reference: In Redux Framework options file, the code used to get categories is
Why am I getting «invalid argument being supplied for foreach»?
I am creating a search within my database and when I used the foreach construct for my results to be echoed I’m getting «invalid argument being supplied for foreach..». What I don’t understand is why this error is coming up because the foreach containing my errors works fine.
The part of the search_results function that’s being focused on is this
I am still new to programming so I understand if there is something I may have missed or just not quite get. I would greatly appreciate any tips or constructive criticism.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Not the answer you’re looking for? Browse other questions tagged php arrays foreach or ask your own question.
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.


































