3v4l.org

run code in 300+ PHP versions simultaneously
<?php class Foo { private $a; protected $b; public $c; } class FooCountable implements \Countable { private $elements = [1,2,3]; public function count() { return count($this->elements); } } $tests = [ 'array' => [1,2,3], 'string' => 'hello world', 'number' => 123, 'iterator' => new \ArrayIterator([1,2,3]), 'countable' => new \FooCountable(), 'zero' => 0, 'string_zero' => '0', 'object' => new \Foo(), 'stdClass' => new \stdClass, 'null' => null, 'empty' => '', 'boolt' => true, 'boolf' => false ]; function countValid($array_or_countable, $mode = \COUNT_NORMAL) { if ( (\PHP_VERSION_ID >= 70300 && \is_countable($array_or_countable)) || \is_array($array_or_countable) || $array_or_countable instanceof \Countable ) { return \count($array_or_countable, $mode); } return null === $array_or_countable ? 0 : 1; } foreach($tests as $key => $test) { echo $key . ': ' . print_r(countValid($test), 1) . \PHP_EOL; } echo 'undefined: ' . print_r(countValid($undefined), 1) . \PHP_EOL;

preferences:
58.48 ms | 402 KiB | 5 Q