Magento – How to Fix Parameter must be an array or an object that implements Countable

errormagento-1.9PHPphp-7.2

After upgrading to PHP 7.2 I get a lot of Warnings

Parameter must be an array or an object that implements Countable

I've tried many ways to fix it but none have worked so far. The commented lines below are my attempts. How can I fix this?

$bannerGroupCode = $this->getBannerGroupCode();
$data = $this->getDataByGroupCode($bannerGroupCode);
$bannerGroupData = $data['group_data'];
$template = '';
  if (count($bannerGroupData) > 0):
// if (empty($bannerGroupData)):
// if ($bannerGroupData && count($bannerGroupData) >= 0):
// if (is_array($bannerGroupData) && count($bannerGroupData) > 0):
// if (strlen($bannerGroupData) > 0):
    $prebaneff = $bannerGroupData->getPreBannerEffects();
    $bannerType = $bannerGroupData->getAnimationType();

Best Answer

There is a function available in PHP (>=7.3) which checks if a variable is countable is_countable

Try it like

if (is_countable($bannerGroupData) && count($bannerGroupData) > 0):
    // Your code
endif;

If the function is not available, you can use below

if (($bannerGroupData instanceof Countable) || is_array($bannerGroupData)) && count($bannerGroupData) > 0):
    // Your code
endif;