1

Invalid argument supplied for foreach() on Line 865

I'm Getting this error permanently:

  foreach ($prod as $key => $value) {
            $product[$key] = $prod[$key];
        }
        if ($prod["visibility"] == 'true') {
            if($this->storage->section["template"]=='')
                $this->storage->content = template('product', $product);
            else
                $this->storage->content = template('product', $product);
                // $this->storage->content = template('custom/'.$this->storage->section["template"], $product);
        }
        return;
    }
Deep Kakkar
  • 5,831
  • 4
  • 39
  • 75
ULTRAMAX
  • 101
  • 1
  • 17

1 Answers1

1

It seems that your array $prod is empty.

Add a condition empty() before foreach like this:

if (! empty($prod)) {
  foreach ($prod as $key => $value) {
    // Your Code
  }
}
else {
  // No records found
}

This will check if the array provided to foreach is not empty and loop over it only if it has records.

Thus, it will not show any errors/warnings.

Also, please go through your code and check why $prod is not getting data.

Is it a condition that is causing no data or there is some error.

That will solve this problem permanently along with above solution.

Pupil
  • 23,834
  • 6
  • 44
  • 66
  • 2
    Just a note: this could be considered a hack IN CASE there should be `prods`. What I'm saying is that the op should also look for the REASON behind the empty `$prod` ^^. **Edit:** checking for `is_array` or something like that would be even better to prevent that type of error (because if `$prod` is `5`, for example, it will still be `!empty` - but invalid for a `foreach`) – FirstOne Mar 14 '16 at 12:48
  • @FirstOne, your suggestion is added in my answer. Thank your for pointing it out. – Pupil Mar 14 '16 at 12:51
  • 1
    Sorry but, I just noted this xD: _It seems that your array `$prod` is empty_. That is not true. `$foo = array();` is an empty array and it is a valid argument for a `foreach` - it just won't enter the `foreach`, but it still won't throw that error. This causes this answer to be a bit off. As I mentioned in the other comment: _if `$prod` is `5`, for example, it will still be `!empty` - but invalid for a `foreach`_ – FirstOne Mar 14 '16 at 13:06
  • Thank You All for your quick reply I edited and Changed as if (! empty($prod)) { foreach ($prod as $key => $value) { $product[$key] = $prod[$key]; } } I'll check it for the error – ULTRAMAX Mar 14 '16 at 13:19