2
votes

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.

4
Rather than attempt to ignore the error, you should try to fix the problem given that it will most likely effect the running of your app.Phil
See the migration guide and do a find on Warn when counting non-countable typesRiggsFolly
Good luck, that may not be as simple as it sounds :) WP Code is the nastiest code I have seen in my lifeRiggsFolly
Can you advise what $this is? Just because it's in WP doesn't mean it's "WordPress code". Better would be to edit the answer and include the results of var_dump($this->xprop). Not to dispute RiggsFolly - major props to him - but I actually doubt this is WP core code....random_user_name
If it's a plugin, get in touch with the maintainers and / or file a bug reportPhil

4 Answers

4
votes

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

1
votes

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

1
votes

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

rfc/counting_non_countables

0
votes

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