<?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
];
if (!\function_exists('is_countable')) {
function is_countable($value)
{
echo 'used shim ';
return \is_array($value) || $value instanceof \Countable;
}
}
function countValid($array_or_countable, $mode = \COUNT_NORMAL)
{
if (\is_countable($array_or_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;
}
preferences:
63.42 ms | 402 KiB | 5 Q