|
-
Sep 7th, 2004, 05:55 AM
#1
Thread Starter
Junior Member
Invalid argument supplied for foreach()
Here is what I have...
An array - $result_array
..and then I have a for and foreach which write the contents of each array within the $result_array array to a table:
PHP Code:
for ($c = 0; $c <= $result_array; $c++) {
echo " <tr>\n";
foreach ($result_array[$c] as $data){
echo " <td>$data</td>\n";
}
echo " </tr>\n";
}
The table gets written out fine, but I get an infinite loop that gives me this error:
Warning: Invalid argument supplied for foreach() in <snip>loop.php on line 205
I figure I'm probably missing something obvious. Any help appreciated,
Thanks, Norm
I am Remus, come from the dead
-
Sep 7th, 2004, 07:14 AM
#2
I've never heard that it's valid to compare an integer to an array, neither is there any indication in the PHP docs that it is so. This is not perl, after all.
Even if it were, even if it yielded the number of elements in the array, using <= would be invalid and would attempt to access one element past the end.
Furthermore, because array entries can have string indices, you're not even guaranteed to get anything by looping a numeric index.
There are only two reliable ways of looping over complete arrays, and those are foreach and while(each) loops. There's no reason not to use them either.
Code:
foreach($result_array as $subarray) {
echo " <tr>\n";
foreach ($subarray as $data){
echo " <td>$data</td>\n";
}
echo " </tr>\n";
}
All the buzzt
 CornedBee
"Writing specifications is like writing a novel. Writing code is like writing poetry."
- Anonymous, published by Raymond Chen
Don't PM me with your problems, I scan most of the forums daily. If you do PM me, I will not answer your question.
-
Sep 7th, 2004, 07:20 AM
#3
Frenzied Member
Umm... maybe because $result_array is not a number?? You need to find out how many elements are in the array and only loop to that many. I would suggest using the count() function to get the number of elements in the array, but keep in mind, you'll have to use just the < operator as the count will be starting from 1, not zero.
And it just occurred to me that your current code may be correct, except for what I just mentioned. Make it < rather than <= and see if that works.
-
Sep 7th, 2004, 07:26 AM
#4
Thread Starter
Junior Member
Yep.
for ($c = 0; $c < sizeof($result_array); $c++)
Thanks
I am Remus, come from the dead
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|