php计数在我的数组中无法正常工作

时间:2019-02-19 15:07:28

标签: php arrays

我打印php数组为空时打印1

$addresses = $user->myFunction();
print_r(count($addresses['my_test']));
Array
(
    [my_test] => Array
        (
            [test] => test
            [test1] => test1
        )

)

打印2

当我打印这张纸时

Array
(
    [my_test] => Array
        (
            [] => 
        )

)

我有1

我不知道这里出了什么问题

如何打印此值?

2 个答案:

答案 0 :(得分:1)

数组计算所有元素,包括空元素。您的输出正确,因为第二个数组有1个元素。

请考虑使用array_filter来避免它们。

示例:

$a = array("" => "");
echo count($a). PHP_EOL; // echo 1
$a = array_filter($a);
echo count($a). PHP_EOL; // echo 0

在这种情况下:

 print_r(count(array_filter($addresses['my_test'])));

答案 1 :(得分:0)

Array
(
    [my_test] => Array
        (
            [test] => test
            [test1] => test1
        )

)
print_r(count($addresses['my_test'])); // it will show 2 cause you have 2 values inside my_test key.

print_r(count($addresses)); // it will show 1 cause you have one value inside main array

Array
(
    [my_test] => Array
        (
            [] => 
        )

)

print_r(count($addresses['my_test'])); // it will show 0 because you have 0 values inside my_test key.

print_r(count($addresses)); //it will show 1 because you have one value my_test inside your main array.

希望它可以帮助您弄清计数功能。