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

This is a very common error when we pass the non-array to count() function. You will get exact same error message like below-

WARNING count(): Parameter must be an array or an object that implements Countable on line number 3

Suppose you have a variable called foo and you have initialize it by bar. Now if you will pass foo to count() function, you will get the above warning.

	$foo = "bar";
	echo count($foo);

So the count() function in PHP will return the number of elements in an array. For the above example, $foo is not an array and count() accept the array as its parameter.

Also Read : Check if a string contains a specific word in PHP?

How to fix Parameter must be an array or an object in count()?

Never ever trust a variable type. You don’t know that your variable is an array or an object if you don’t expecitly declare it as an array or object.

Suppose you want to fetch all active user from MySQL database and store it into the $active_user variable. But if there is no active user present and if you pass the $active_user to count($active_user), it will give you the above warning. So first check if the variable is array or object.

How to check that?

If you are using PHP >= 7.3 you can use is_countable(). Check the below code:

Also Read : How to target a specific city to show your website in PHP?

if(is_countable($foo)) {
    echo count($foo);

If you are using PHP >= 7.1 you can use is_iterable(). Check the below code:

if(is_iterable($foo)) {
    echo count($foo);

About Ashis Biswas

A web developer who has a love for creativity and enjoys experimenting with the various techniques in both web designing and web development. If you would like to be kept up to date with his post, you can follow him.

Leave a Comment