Php Invalid Argument Supplied For Foreach

It frequently happens to me to manage data that can be either an variety or a null variable and also to feed some foreach with these information.

You watching: Php invalid argument supplied for foreach

$values = get_values();foreach ($worths as $value) ...When you feed a foreach with data that are not an variety, you gain a warning:

Warning: Invalid argument gave for foreach() in <...>

Assuming it"s not feasible to refactor the get_values() attribute to constantly return an range (backward compatibility, not available resource code, whatever various other reason), I"m wondering which is the cleacolony and most reliable way to protect against these warnings:

Casting $values to arrayInitializing $values to arrayWrapping the foreach through an ifOther (please suggest)
php foreach
Share
Follow
edited Sep 21 "16 at 16:52
*

Geoffrey Hale
8,41044 gold badges3535 silver badges4242 bronze badges
asked Apr 13 "10 at 13:48
*

Roberto AloiRoberto Aloi
29k1919 gold badges6565 silver badges109109 bronze badges
1
Add a comment |

19 Answers 19


Active Oldest Votes
577
Personally I find this to be the many clean - not certain if it"s the a lot of effective, mind!

if (is_array($values) || is_object($values)) foreach ($worths as $value) ... The reason for my choice is it does not alfind an empty range when you"ve got nopoint to begin with anymeans.


Share
Follow
edited Oct 27 "15 at 20:57
*

vlasits
2,18011 gold badge1212 silver badges2727 bronze badges
answered Apr 13 "10 at 13:51
*

Andy ShellamAndy Shellam
14.6k11 gold badge2424 silver badges4141 bronze badges
10
| Sjust how 5 more comments
144
How about this one? lot cleaner and all in single line.

foreach ((array) $items as $item) // ...
Share
Follow
answered Apr 8 "15 at 17:08

*

Ajith R NairAjith R Nair
1,92211 gold badge1313 silver badges1010 bronze badges
7
| Sexactly how 2 more comments
47
I typically usage a construct equivalent to this:

/** * Determine if a variable is iterable. i.e. have the right to be used to loop over. * *
rerevolve bool */feature is_iterable($var)$worths = get_values();if (is_iterable($values)) foreach ($worths as $value) // execute stuff... Keep in mind that this particular version is not tested, its typed straight into SO from memory.

Edit: added Traversable check


Share
Follow
edited May 25 "15 at 13:47
answered Mar 27 "13 at 9:30
KrisKris
36.7k99 gold badges6969 silver badges9595 bronze badges
10
| Sexactly how 5 even more comments
17
Please do not depfinish on casting as a solution,even though others are arguing this as a valid alternative to prevent an error, it can reason an additional one.

Be aware: If you suppose a certain form of range to be reverted, this could fail you. More checks are compelled for that.

E.g. casting a boolean to an variety (array)bool, will certainly NOT result in an empty selection, yet an variety via one element containing the boolean value as an int: <0=>0> or <0=>1>.

I wrote a quick test to current this problem.(Here is a backup Test in case the first test url stops working.)

Included are tests for: null, false, true, a course, an array and undefined.

Always test your input before utilizing it in foreach. Suggestions:

Wrapping foreach within ifUsing trycatch() blocksDesigning appropriate code / testing before manufacturing releasesAlmethods extract your helper approaches into the global namespace in a method to reduce duplicate code
Share
Follow
edited May 23 "17 at 12:10
Community♦
111 silver badge
answered Sep 26 "15 at 17:54
AARTTAARTT
45355 silver badges88 bronze badges
Add a comment |
9
Try this:

//Force array$dataArr = is_array($dataArr) ? $dataArr : array($dataArr);foreach ($dataArr as $val) echo $val;;)


Share
Follow
edited Jul 30 "18 at 12:52
answered Jun 12 "14 at 23:06
GigolNet GuigolachviliGigolNet Guigolachvili
66377 silver badges66 bronze badges
1
Add a comment |
6
$values = get_values();foreach ((array) $values as $value) ...Problem is constantly null and also Casting is in truth the cleaning solution.


Share
Follow
edited Mar 2 "16 at 16:59
answered Mar 2 "16 at 14:25
boctulusboctulus
32677 silver badges1313 bronze badges
0
Add a comment |
5
If you"re using php7 and also you want to handle only undefined errors this is the cleaswarm IMHO

$range = <1,2,3,4>;foreach ( $selection ?? <> as $item ) echo $item;
Share
Follow
answered Aug 9 "16 at 15:27
Edwin RodríguezEdwin Rodríguez
1,13088 silver badges1717 bronze badges
0
Add a comment |
4
First of all, eincredibly variable should be initialized. Almethods.Casting is not an choice.if get_values(); have the right to rerotate different form variable, this worth have to be checked, of course.


Share
Follow
answered Apr 13 "10 at 14:11
Your Typical SenseYour Usual Sense
154k3434 gold badges197197 silver badges317317 bronze badges
3
Add a comment |
3
More concise extension of
Kris"s code

attribute secure_iterable($var) rerotate is_iterable($var) ? $var : array();foreach (secure_iterable($values) as $value) //do stuff...especially for utilizing inside template code

...
Share
Follow
edited May 23 "17 at 11:33
Community♦
111 silver badge
answered Apr 23 "15 at 12:38
HongKilDongHongKilDong
1,23733 gold badges1515 silver badges2222 bronze badges
1
Add a comment |
2
There seems likewise to be a relation to the environment:

I had actually that "invalid debate offered foreach()" error just in the dev atmosphere, however not in prod (I am working on the server, not localhost).

See more: How Many Feet Is 4 Stories High In Meters? Height Standards

Despite the error a var_dump shown that the variety was well tright here (in both instances app and dev).

The if (is_array($array)) about the foreach ($variety as $subarray) fixed the difficulty.

Sorry, that I cannot explain the cause, but as it took me a while to figure a solution I believed of better sharing this as an monitoring.


Share
Follow
answered Feb 22 "15 at 11:36
araldharaldh
5166 bronze badges
Add a comment |
2
Exceptional situation for this notice occurs if you collection array to null inside foreach loop

if (is_array($values)) foreach ($values as $value) $values = null;//WARNING!!!
Share
Follow
answered Jan 18 "16 at 9:24
Farid MovsumovFarid Movsumov
10.9k88 gold badges6767 silver badges9292 bronze badges
Add a comment |
2
Warning invalid discussion provided for foreach() display tweets.go to /wp-content/plugins/display-tweets-php.Then insert this code on line number 591, It will certainly run perfectly.

if (is_array($tweets)) foreach ($tweets as $tweet) ...
Share
Follow
edited Sep 12 "19 at 9:30
Nik
2,16022 gold badges1818 silver badges2323 bronze badges
answered Apr 10 "15 at 7:59
Saad KhananiSaad Khanani
2911 bronze badge
1
Add a comment |
2
foreach ($arr ?: <> as $elem) // Do somethingThis doesen"t examine if it is an range, however skips the loop if the variable is null or an empty range.


Share
Follow
edited Jul 8 "20 at 19:37
answered Dec 18 "15 at 9:31
T30T30
9,28755 gold badges4444 silver badges5656 bronze badges
1
Add a comment |
1
I am not certain if this is the case however this problem appears to happen a variety of times once moving wordpress sites or moving dynamic sites in basic. If this is the instance make sure the hosting you are migrating to offers the very same PHP version your old website provides.

If you are not migrating your site and this is simply a difficulty that has actually come up attempt updating to PHP 5. This takes care of some of these troubles. Might seem like a silly solution however did the trick for me.


Share
Follow
answered Jul 12 "14 at 13:16
ErikErik
3755 bronze badges
Add a comment |
1
Use is_range attribute, when you will pass range to foreach loop.

if (is_array($your_variable)) foreach ($your_variable as $item) //your code
Share
Follow
answered Oct 21 "17 at 21:46
Muhammad BilalMuhammad Bilal
1,6821515 silver badges3434 bronze badges
Add a comment |
1
How around this solution:

$kind = gettype($your_iteratable);$kinds = array( "array", "object");if (in_array($type, $types)) // foreach code comes here
Share
Follow
answered Nov 1 "17 at 12:04
JulianJulian
3,22922 gold badges3030 silver badges4444 bronze badges
Add a comment |
1
What about defining an empty selection as fallearlier if get_value() is empty?I can not think of a shortest means.

$values = get_values() ?: <>;foreach ($worths as $value) ...
Share
Follow
answered Mar 18 "19 at 22:27
Quentin VeronQuentin Veron
2,53011 gold badge1010 silver badges2727 bronze badges
Add a comment |
1
I"ll use a mix of empty, iscollection and also is_selection as

$variety = <"dog", "cat", "lion">;if (!empty($array) && isset($array) && is_array($array) //loop foreach ($variety as $values) echo $values;
Share
Follow
edited Sep 12 "19 at 9:38
Nik
2,16022 gold badges1818 silver badges2323 bronze badges
answered Oct 6 "17 at 17:10
RotimiRotimi
4,54344 gold badges1616 silver badges2727 bronze badges
Add a comment |
-2
i would certainly do the exact same thing as Andy however i"ld use the "empty" function.

choose so:

if(empty($yourArray))echo"There"s nothing in the selection.....

";elseforeach ($yourArray as $current_array_item) //perform something through the current array item below
Share
Follow
answered Sep 30 "12 at 17:40
as_bold_as_loveas_bold_as_love
21644 silver badges1111 bronze badges
2
Add a comment |
Highly active question. Earn 10 reputation (not counting the association bonus) in order to answer this question. The reputation need helps protect this question from spam and non-answer activity.

Not the answer you're looking for? Browse other inquiries tagged php foreach or ask your own question.


The Overflow Blog
Featured on Meta
Linked
127
cleanest way to skip a foreach if array is empty
0
Invalid argument provided for foreach!
0
Not to loop the vital with empty value in a multidimensional array
1
PHP foreach reasons “Invalid debate offered for foreach()”
-3
Why always “Invalid argument gave for foreach”
-1
Error “Invalid discussion offered for foreach()” on my function
0
Warning: Invalid dispute offered for foreach() in php
-2
PHP Warning: Illegal string balance out & Invalid dispute supplied for foreach()
-3
Why the warning is coming as “Warning: Invalid discussion gave for foreach() in /var/www/smart-rebate-web/model/RebateByProduct.php on line 53”?
1
Invalid argument provided for foreach() “Invalid Argument”
See more attached questions
Related
1077
How carry out you get the index of the existing iteration of a foreach loop?
1592
How does the Java 'for each' loop work?
778
LINQ tantamount of foreach for IEnumerable
0
invalid debate gave for foreach
1
Invalid discussion gave for foreach() - using glob
1752
Is tbelow a reason for C#'s reuse of the variable in a foreach?
5114
For-each over an range in JavaScript
2146
How does PHP 'foreach' actually work?
1208
Reference - What does this error intend in PHP?
Hot Network Questions more warm concerns
Concern feed
Subscribe to RSS
Concern feed To subscribe to this RSS feed, copy and paste this URL into your RSS reader.


lang-php
Stack Overcirculation
Products
Company
Stack Exchange Network
website style / logo © 2021 Stack Exadjust Inc; user contributions licensed under cc by-sa. rev2021.8.30.40094


Stack Overcirculation functions ideal via JavaScript enabled
*

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can save cookies on your device and also disclose indevelopment in accordance with our Cookie Policy.