The is_countable Function

The is_countable function checks whether it is possible to count the number of elements in a variable. It returns true if the variable is an array or an object implementing the Countable interface. Otherwise, it returns false.

Syntax

phpis_countable(mixed $value): bool

Example

Let's check an array for the possibility of counting elements:

php<?php
  $arr = [1, 2, 3];
  var_dump(is_countable($arr));
?>

Code execution result:

phptrue

Example

Let's check a string for the possibility of counting elements:

php<?php
  $str = 'abcde';
  var_dump(is_countable($str));
?>

Code execution result:

phpfalse

Example

Let's check an object implementing the Countable interface:

php<?php
  class MyCountable implements Countable {
    public function count(): int {
      return 5;
    }
  }
  
  $obj = new MyCountable();
  var_dump(is_countable($obj));
?>

Code execution result:

phptrue

See Also

  • the is_array function,
    which checks if a variable is an array
  • the count function,
    which counts the number of elements in an array