I'll-Be-Back
I'll-Be-Back

Reputation: 10828

Why does count() return more than 0 when there is no element in an array?

If there are no elements in a array, why does count() return more than 0?

if (count($_POST['tickboxes']) > 0) {
           echo "found";
}

$POST array structure:

Array
(
    [ID] => 53
    [tickboxes] => 
    [dropdowns] => 
)

I was expecting 0 or null.

Upvotes: 1

Views: 1083

Answers (3)

Ariel
Ariel

Reputation: 26753

You are trying to countDocs something that is not an array, but rather a string.

As documented, count returns 1 for strings, regardless of their lengths.

You can use the strlenDocs function instead, as it counts the number of ascii characters in that string:

if (strlen($_POST['tickboxes']) > 0) {
           echo "found";
}

Additionally, you can use the emptyDocs language construct for this, it will check if it's an empty array or a blank string, or the integer 0 or the string '0' - and that last one may cause you grief (depending on what you are doing with it, i.e. if your users can send you such input).

If empty would be an option for you, you can just spare that as well:

if ($_POST['tickboxes']) {
           echo "found";
}

Don't forget to check if that key in the $_POST array exists if you do so. If you're unsure, empty won't give you any warning:

if (!empty($_POST['tickboxes'])) {
           echo "found";
}

Upvotes: 9

Catalin
Catalin

Reputation: 868

That would be because your variable is not an array. Try echo count(''); and you'll see it returns 1 while count(array()) will be 0.

Upvotes: 3

SamarLover
SamarLover

Reputation: 182

i think @Ariel solve it

if you sending data from html form you can use tamperdata addons in firefox

https://addons.mozilla.org/en-US/firefox/addon/tamper-data/

this will help you :)

Upvotes: 0

Related Questions