不用for/foreach/while/count获取一维数组元素的个数

刚才公司技术群里讨论一个题目:不用for/foreach/while/count(),怎么获取一维数组的元素的个数?

有人使用implode + strlen配合使用,有人用array_map,array_walk。一时心痒,也来一段,直接看代码:

function array_count($arr) {
    if (!is_array($arr)) {
        trigger_error("Expect Array", E_USER_WARNING);
        return false;
    }
    if (empty($arr)) {
        return 0;
    }
    reset($arr);
    $count = 1;
    begin:
        if (false === next($arr)) {
            if (null !== key($arr)) {
                ++$count;
                goto begin;
            }
        } else {
            ++$count;
            goto begin;
        }
    return $count;
}

echo array_count(123), "\n";
echo array_count(array()), "\n";
echo array_count(array(1)), "\n";
echo array_count(array('k' => 2)), "\n";
echo array_count(array('k' => 2, 2)), "\n";
echo array_count(array('k' => 2, 2, 3)), "\n";
echo array_count(array('k' => 2, false, 2, 3)), "\n";
echo count(array('k' => 2, false, 2, 3)), "\n";
echo array_count(array('k' => 2, null, false, 2, 3)), "\n";


你可能感兴趣的:(不用for/foreach/while/count获取一维数组元素的个数)