What is the is_countable method in PHP?

The is_countable() method can be used to check if a variable is a countable value or not.

Syntax


is_countable(mixed $value): bool

Return value

This method returns true if the passed value is countable. Otherwise, it returns false.


The countable value means an array or an object that implements the Countable class.

Code

<?php
class MyCounter implements Countable {
public function count() {
return 0;
}
}
$test = new MyCounter();
printIsCountable($test);
$test = [1];
printIsCountable($test);
$test = 'true';
printIsCountable($test);
function printIsCountable($test){
echo "The Value is: ";
var_dump($test);
echo "Is Countable: ";
var_dump(is_countable($test));
echo "---------\n\n";
}
?>

Explanation

In the code above:

  • We have created a MyCounter class that implements the Countable class. Then we created an object for the class. We called the is_countable method with that object as an argument. In this case, we will get true as result.

  • We called the is_countable method with an array as an argument. For an array, the is_countable method returns true.

  • We called the is_countable method with a string as an argument. Now we will get false as the return value because the string is not a countable value.

Free Resources