Craft 3 Module Working but Throwing Errors in web.log I'm seeing a lot of "Invalid argument" errors in the web.log for a "Multiple Option Variant" module I have running. It seems to be working just fine on the site, but curious as to what the issue might be. Do I need to put in some "guards" in the code, and if so, what would that look like?

This is the error;

[error][yii\base\ErrorException:2] yii\base\ErrorException: Invalid argument supplied for foreach() in /httpd.www/craft/modules/multipleoptionvariantmodule/src/variables/MultipleOptionVariantModuleVariable.php:52
#0 /httpd.www/craft/vendor/craftcms/cms/src/web/ErrorHandler.php(76): yii\base\ErrorHandler-&gt;handleError(2, 'Invalid argumen...', '/httpd.www/...', 52)
#1 /httpd.www/craft/modules/multipleoptionvariantmodule/src/variables/MultipleOptionVariantModuleVariable.php(52): craft\web\ErrorHandler-&gt;handleError(2, 'Invalid argumen...', '/httpd.www/...', 52, Array)


The referenced file at looks like this—and it seems to be the foreach function that's the culprit;

namespace modules\multipleoptionvariantmodule\variables;

use modules\multipleoptionvariantmodule\MultipleOptionVariantModule;

use Craft;

class MultipleOptionVariantModuleVariable
{
     public function getUniqueVariantAttributeValues($fieldName, $variants, $onlyInStock=false) {
         $addedIds = array();
         $sizes = array();

         foreach($variants as $variant) {
             $outOfStock = (($variant-&gt;stock &lt;= 0) &amp;&amp; ($variant-&gt;hasUnlimitedStock == false));

             if (!$onlyInStock || ($onlyInStock &amp;&amp; !$outOfStock)) {
                 if (isset($variant-&gt;{$fieldName}[0])) {
                     if (array_search($variant-&gt;{$fieldName}[0]-&gt;slug, $addedIds, true) === false) {
                         $sizes[] = $variant-&gt;{$fieldName}[0];
                         $addedIds[] = $variant-&gt;{$fieldName}[0]-&gt;slug;
                     }
                 }
             }
         }

         return $sizes;
    }
}


This is then how that is used in the template(s);

{% set variants = product.variants %}
{% set variantColors = craft.multipleOptionVariantModule.getUniqueVariantAttributeValues('variantColor', variants, false) %}
{% set variantTypes = craft.multipleOptionVariantModule.getUniqueVariantAttributeValues('variantType', variants, false) %}


I'd take any hints on how to convert that php functionality to pure twig too. :)
That would actually be ideal.
You'll get that error in PHP when you try to iterate over a variable that isn't an array.

My guess is you'd be able to guard against it with something like:

if (is_array($variants)) {
    foreach($variants as $variant) {
    ...
    }
}