1

i print php array when it's empty it print 1

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

)

it print 2

when i print this

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

)

i got 1

i don't know what is the problem here

How to print exact value of this?

my Test
  • 105
  • 1
  • 10
  • 5
    you still have one empty array inside, nothing is wrong in the count result – Frankich Feb 19 '19 at 15:09
  • Check your `$user->myFunction()` you may not return what you think it should. And you can always call `array_filter` to avoid empty element and then count – dWinder Feb 19 '19 at 15:11

2 Answers2

1

Array count all element including empty ones. Your output is correct as you second array has 1 element.

Consider use array_filter to avoid them.

Example:

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

In you case:

 print_r(count(array_filter($addresses['my_test'])));
dWinder
  • 11,597
  • 3
  • 24
  • 39
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.

Hope it helps you clarify count function.

Rohit Mittal
  • 2,064
  • 2
  • 8
  • 18