How to Checks whether the contents of a variable is a countable value in PHP ?
In PHP, we can check whether the contents of a variable is a countable value or not using the is_countable()
function. This function was introduced in PHP 7.3.
The is_countable()
function returns true
if the given variable is an array or an object that implements the Countable
interface. Otherwise, it returns false
.
Here's an example:
// Example 1: Countable value
$array = [1, 2, 3];
if (is_countable($array)) {
echo "The variable is countable.";
} else {
echo "The variable is not countable.";
}
// Output: The variable is countable.
// Example 2: Non-countable value
$string = "Hello, world!";
if (is_countable($string)) {
echo "The variable is countable.";
} else {
echo "The variable is not countable.";
}
// Output: The variable is not countable.
In the above example, we have used the is_countable()
function to check whether the $array
variable is countable or not. Since $array
is an array, the function returns true
and the output is "The variable is countable."
Similarly, we have used the is_countable()
function to check whether the $string
variable is countable or not. Since $string
is a string and not an array or an object that implements the Countable
interface, the function returns false
and the output is "The variable is not countable."