无论如何要计算一个数组在 PHP 中有多少个键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4106412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 11:59:31  来源:igfitidea点击:

Is there anyway to count how many keys an array has in Php?

phparrayscountkey

提问by Mohammad

Array
    (
        [0] => 'hello'
        [1] => 'there'
        [2] => 
        [3] => 
        [4] => 3
    )

// how to  get the number 5?

回答by teemitzitrone

count

数数

$arr = Array
    (
        0 => 'hello',
        1 => 'there',
        2 => null,
        3 => null,
        4 => 3,
    );
var_dump(count($arr));

Output:

输出:

int(5)

整数(5)

回答by MatTheCat

回答by Phill Pafford

Works for me w/ NULL

为我工作,带 NULL

$array = array('hello', 'there', NULL, NULL, 3);

echo "<pre>".print_r($array, true)."</pre><br />";
echo "Count: ".count($array)."<br />";

output

输出

Array
(
    [0] => hello
    [1] => there
    [2] => 
    [3] => 
    [4] => 3
)

Count: 5

A quick Google search for PHP Arrayshould pull up results of all the functions available

Google 上快速搜索 PHP Array应该可以找到所有可用函数的结果

回答by David Kurid?a

Below code was tested with PHP 5.3.2. and the output was int 5.

下面的代码是用 PHP 5.3.2 测试的。输出为int 5.

$a = array(
    0 => 'hello',
    1 => 'there',
    2 => null,
    3 => null,
    4 => 3,
);

var_dump(count($a));

Can you please provide more information about nullnot being counted? An older version maybe? Or simply messing with the rest of us? :)

你能提供更多关于null不被计算在内的信息吗?可能是旧版本?还是干脆逗弄我们其他人?:)

EDIT: well, posted wrong code :)

编辑:好吧,发布了错误的代码:)

回答by Martin Bean

echo count($array);