计算数组键

时间:2014-01-03 16:34:40

标签: php arrays

Array
(
[0] => Array
    (
        [name] => WWW
    )

[1] => Array
    (
        [name] => Hi
    )

[2] => Array
    (
        [name] => Hello
    )

[3] => Array
    (
        [name] => World
    )

)

我有上面的数组,我想计算键的数量。

使用以下代码时

$temp = array_keys($array);
echo $temp;

结果是2而不是4(0,1,2,3)。我做错了什么?

3 个答案:

答案 0 :(得分:4)

您需要对数组进行计数才能获得数字:

  $arr = array
    (
        "0" => array
        (
            "name" =>"WWW"
        ),

    "1" => array
    (
        "name" => "Hi"
    ),

    "2" => array
    (
        "name" => "Hello"
    ),

    "3" => array
    (
        "name" => "World"
    )

    );

    $keys_count = count($arr);
    echo $keys_count;

答案 1 :(得分:4)

只计算数组本身:count($array)

总有与数值相同的密钥数量!

答案 2 :(得分:-1)

非常简单的伙伴。看这个:

 $array = array(0 => 100, "color" => "red");
 print_r(count($array));

php.net 为大家提供帮助! ;)