-1

I have been looking for some time the solution to eliminate my error message :

Warning: Invalid argument supplied for foreach() in...

Here is my code :

    $data = $_POST;

    if (count($data) > '1') {
        var_dump($data);

        foreach ($data as $k => $row) {
            var_dump($row);

                foreach ($row as $k2 => $img) {
                    echo $img;
                }
        }

Here's the result : (The result is good only the error message here is annoying)

array (size=2)
  'image' => 
    array (size=2)
      0 => string '608' (length=3)
      1 => string '610' (length=3)
  'submit' => string 'Save' (length=11)
array (size=2)
  0 => string '608' (length=3)
  1 => string '610' (length=3)

608610

string 'Save' (length=11)

I tried to add a isset for $data, without success ..

Paul
  • 352
  • 3
  • 6
  • 17
  • 1
    supply array value to inner foreach. Check for `is_array` before sending to it – Thamilhan Apr 15 '17 at 10:25
  • _Side note:_ `count($data) > '1'` should be `count($data) > 1`. I know it works either way, but it makes no sense to make the parser cast the string `'1'` as an integer when you can write it properly from the start. – M. Eriksson Apr 15 '17 at 10:27
  • 4
    Possible duplicate of [Invalid argument supplied for foreach()](http://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach) – Thamilhan Apr 15 '17 at 10:27

2 Answers2

0

You should use is_array and count for checking whether a variable is array or not and whether it is an empty array or not.

<?php

$data = $_POST;

if (count($data) > 1)
{
    var_dump($data);

    foreach ($data as $k => $row)
    {
        var_dump($row);

        if(is_array($row) && count($row)>0)//you should add this.
        {
            foreach ($row as $k2 => $img)
            {
                echo $img;
            }
        }
    }
}
Sahil Gulati
  • 15,028
  • 4
  • 24
  • 42
0

The problem belongs in the nature of the 'submit' field. In the first foreach, the first cycle will have $k = images and $value will be an array, while the second cycle will be $k = submit and $value = a string. The internal foreach tries to loop in a string as a key -> value array, thus being not possible... So the solution would be using only a foreach on $data['images'] or making the submit value an array. The former solution seems the more appropriate for you!

Loris Topa
  • 91
  • 2