Michal
Michal

Reputation: 3368

foreach "Invalid argument supplied" when supplying array

I am getting a Invalid argument supplied for foreach() warning that I have no explanation for.

Everything works as expected, however it seems that foreach() does not like an array as argument even if the array contains another array (so valid for foreach())?

I have the following code:

foreach ( $distr_continents[$continent_id] as $distributor_data )
{
    echo('<td>' . $distributor_data . '</td>');
}

The $distr_continents[$continent_id] looks like this:

 Array
 (
  [2] => Array
    (
        [0] => <td valign="top"></td>
        [1] => <td valign="top"></td>
    )

  [1] => Array
    (
        [0] => <td valign="top"></td>
        [1] => <td valign="top"></td>
    )

  [4] => Array
    (
        [0] => <td valign="top"></td>
        [1] => <td valign="top"></td>
        [2] => <td valign="top"></td>
        [3] => <td valign="top"></td>
        [4] => <td valign="top"></td>
        [5] => <td valign="top"></td>
        [6] => <td valign="top"></td>
        [7] => <td valign="top"></td>
        [8] => <td valign="top"></td>
        [9] => <td valign="top"></td>
        [10] => <td valign="top"></td>
    )

  [3] => Array
    (
        [0] => <td valign="top"></td>
        [1] => <td valign="top"></td>
        [2] => <td valign="top"></td>
        [3] => <td valign="top"></td>
        [4] => <td valign="top"></td>
    )

 )

What am I missing here??

Upvotes: 0

Views: 335

Answers (3)

Raheel
Raheel

Reputation: 9024

This might fix your warning.

foreach ( (array) $distr_continents[$continent_id] as $distributor_data )
{
    echo('<td>' . $distributor_data . '</td>');
}

Upvotes: 1

Santosh Pradhan
Santosh Pradhan

Reputation: 149

Make sure $distr_continents[$continent_id] is always an array.

Just encapsulate foreach loop as below.

if(isset($distr_continents[$continent_id]) && is_array($distr_continents[$continent_id])){

   // Your foreach loop here

}

Also you are trying to echo an array. This is wrong and will throw a warning.

Upvotes: 0

kailash sharma
kailash sharma

Reputation: 356

I think the array is multidimensional so you need to run a loop inside also...This is just a reference

hope you are understanding it.

foreach ( $distr_continents[$continent_id] as $distributor_data )
{
      foreach($distributor_data as $d_data){
          echo('<td>' . $d_data . '</td>');
      }
}

Upvotes: 0

Related Questions