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
countablevalue means an array or an object that implements theCountableclass.
Code
<?phpclass 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
MyCounterclass that implements theCountableclass. Then we created an object for the class. We called theis_countablemethod with that object as an argument. In this case, we will gettrueas result. -
We called the
is_countablemethod with an array as an argument. For an array, theis_countablemethod returnstrue. -
We called the
is_countablemethod with a string as an argument. Now we will getfalseas the return value because the string is not acountablevalue.