Warning: count(): Parameter must be an array or an object that implements Countable

magento.stackexchange https://magento.stackexchange.com/questions/264992

  •  21-02-2021
  •  | 
  •  

Pregunta

I have this code:

public function getCounter()
    {
        /** @var \Amasty\ShopbyPage\Model\Page $model */
        $model = $this->_coreRegistry->registry(RegistryConstants::PAGE);
        return count($model->getConditions());
    }

But in line:

return count($model->getConditions());

I get error in php 7.2:

Warning: count(): Parameter must be an array or an object that implements Countable

Magento 2.3 version. PHP7.2

In php 7.1 works fine. How can I fix it?

¿Fue útil?

Solución

Remove count and return direct $model->getConditions() add print_r and check what result you are getting. You will know what you have to do after that

Otros consejos

Best solution would be to update

return count($model->getConditions());

to

return count($model->getConditions()??[]);

as you can't be sure that $model->getConditions() will always be empty. The reason why it's happening, in php7.2 count on null throws warning, see https://www.php.net/manual/en/migration72.incompatible.php "Warn when counting non-countable types" section

Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top