0

How to solve E_WARNING: Invalid argument supplied for foreach() ?

for example:

This is the code

foreach ($response->myinterests as $key => $value) {
     foreach($value as $val)
    {
    $inter[$key][].= $val;
}
}

I want to add condition not equals empty

if(!empty($response->myinterests)){
        foreach ($response->myinterests as $key => $value) {
    foreach($value as $val)
    {
    $inter[$key][].= $val;
    }
}
        }

Is this right?

Darren
  • 13,050
  • 4
  • 41
  • 79
  • 2
    possible duplicate of [Invalid argument supplied for foreach()](http://stackoverflow.com/questions/2630013/invalid-argument-supplied-for-foreach) – Narendrasingh Sisodia Jul 13 '15 at 06:57
  • Yes `!empty($response->myinterests)` is correct you can also use `count($response->myinterests) > 1`. – Manwal Jul 13 '15 at 06:57
  • 1
    `$inter[$key][].=`........? Why concatenate (**`.`**)....? – Darren Jul 13 '15 at 07:06
  • 1
    That warning means that you are trying to traverse a *non-traversable* thing. You can basically traverse arrays and objects, so you must ensure you are giving `foreach` one of these types and not `null` or any scalar value. – Carlos Jul 13 '15 at 07:17
  • Or you could type cast it: `foreach ((array) $response->myinterests as $key => $value) {` However if you get something like 0 which is non-traversable type casting it gives you array ( [0] => 0 ) instead of an empty array. But I prefer the type-cast route. – Ash Jul 13 '15 at 08:36

0 Answers0