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?

2
  • 5
    you still have one empty array inside, nothing is wrong in the count result Commented Feb 19, 2019 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 Commented Feb 19, 2019 at 15:11

2 Answers 2

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'])));
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.