DanCue
DanCue

Reputation: 772

PHP 7.2 Count error

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

I'm getting the above error on the following line.

if (0 >= count($this->xprop))

Can someone help me understand this? I'm fairly new to PHP. The issue is obviously with $this->xprop not being an array. It wasn't an issue before I upgraded to PHP 7.2. How can I get around this? Are code with warnings still being executed or is this going to cause execution to fail?

I've tried to follow the second answer on here with no luck. The accepted answer is not acceptable to me as it is more of a hack.

Upvotes: 2

Views: 12151

Answers (4)

dipser
dipser

Reputation: 442

There are some ways, but I like the new ??-operator, because it is short:

$null = null;

echo count($null);                           // Warning: count(): Parameter must be an array or an object that implements Countable
echo is_countable($null) ? count($null) : 0; // => 0
echo count((array)$null);                    // => 0
echo count($null ?? []);                     // => 0

Upvotes: 1

Gehad Mohamed
Gehad Mohamed

Reputation: 151

if you are using php7.3 or above you can use is_countable before the count

rfc/counting_non_countables

Upvotes: 1

Yassine CHABLI
Yassine CHABLI

Reputation: 3734

the problem is caused because of the PHP version.

In PHP 7.2 , the count() method does not support null as argument .

Example :

in PHP 5.6.x :

echo count(null); // this show 0 

in PHP 7.2.x :

echo count(null); // count(): Parameter must be an array or an object that implements Countable 

So you should verify if the variable is not null

Upvotes: 1

FoulFoot
FoulFoot

Reputation: 654

PHP 7.2 throws an error when trying to count, or get the size of, a variable that isn't set. In previous versions, authors would shortcut checking to see if the variable was set by just counting (or sizeof'ing) it, and getting "0" on an unset variable.

The solution is to check to see if it's set before counting it:

if (isset($this->xprop) && count($this->xprop) == 0)

Your example above is actually negative logic, and is a pretty strange way of stating "if the size of this array is zero, or less than zero" (which is impossible). So, following your example above, the PHP 7.2 compliant version would be to use empty:

if (empty($this->xprop))

... because a variable can be set ($xprop = array()) but still be empty.

Sorry if this is a bit unclear; it's late here!

Foul

Upvotes: 4

Related Questions